<?php

namespace app\app\controller;


use app\common\controller\Homebase;
use EasyWeChat\Factory;
use think\Db;
use util\Date;
use util\File;
use function Symfony\Component\String\u;

class WxUser extends Homebase
{
    protected $openid;
    protected $memberInfo;
    protected $memberId;
    protected $role;
    protected $noRule = ['getGoodsDetail'];

    protected function initialize()
    {
        parent::initialize();
        $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        $data = $this->request;
        if (in_array($data->routeInfo()['rule'], $this->noRule)) {
            if ($authorization) {
                $this->member_init($authorization);
            }
        } else {
            if (empty($authorization)) {
                responseJson(-100, '请先登录');
            }
            $this->member_init($authorization);
        }
    }

    public function member_init($authorization)
    {
        $openid = $authorization;
        $user = Db::name('member')->where('openid', '=', $openid)
            ->field('id,money,level_id,coupon1,coupon2,openid,nickname,avatarUrl,mobile,status,fraction,code_url,invite_id,min_tx,is_clock,is_create_zl')->find();
        if (empty($user)) {
            responseJson(-100, '登录信息有误');
        }
        if ($user['status'] == 0) {
            msg(-200, '用户已冻结', $user);
        }
        if (!strpos($user['avatarUrl'], 'ttp')) {
            $user['avatarUrl'] = config('wechat.url') . $user['avatarUrl'];
        }
        $this->openid = $openid;
        $this->memberInfo = $user;
        $this->memberId = $user['id'];
    }

    //商品详情
    public function getGoodsDetail()
    {
        $data = $this->request->param();
        $goods_info = Db::name('goods')->find($data['id']);
        if (!$goods_info) {
            msg(-1, '商品不存在', '');
        }
        $brand = Db::name('brand')->find($goods_info['brand_id']);
        $goods_info['brand'] = $brand['name'];
        $img = explode(',', $goods_info['img']);
        $goods_info['img'] = $img;

        $goods_attr_value = Db::name('goods_attr_value')->where([
            'goods_id' => $data['id']
        ])->find();
        $goods_info['goods_attr_value'] = $goods_attr_value;

        $goods_info['is_collect'] = $this->isCollect($data['id']);
        //获取商品参数
        $goods_attribute_value = Db::name('goods_attribute_value')
            ->where('goods_id', '=', $data['id'])
            ->select();
        $goods_attribute_value2 = Db::name('goods_attribute_value')
            ->where('goods_id', '=', $data['id'])
            ->column('name');
//        $obj = [
//            [
//                'name' => '简介',
//                'value' => $goods_info['desc']
//            ]
//        ];
//        array_splice($goods_attribute_value, 0, 0, $obj);
        $goods_info['goods_attribute_value'] = $goods_attribute_value;
        $goods_attribute_value2 = implode('/', $goods_attribute_value2);
        $goods_info['goods_attribute_value2'] = $goods_attribute_value2;
        msg(0, '查询成功', $goods_info);
    }

    /**
     * 获取用户信息
     */
    public function getMemberInfo()
    {
        //会员二维码
        if (!$this->memberInfo['code_url']) {
            $code_url = qrcode($this->memberId, '');
            Db::name('member')->update([
                'id' => $this->memberId,
                'code_url' => $code_url
            ]);

        }
        $is_dl = $this->isDl();
        $this->memberInfo['is_dl'] = $is_dl;
//        $level_info = Db::name('member_level')->find($this->memberInfo['level_id']);
//        $this->memberInfo['level_info'] = $level_info;
        msg(0, '查询成功', $this->memberInfo);
    }

    //判断是否代理
    public function isDl()
    {
        $is_dl = Db::name('member_dl')->where([
            'is_del' => 0,
            'member_id' => $this->memberId
        ])->find();
        if ($is_dl) {
            return 1;
        }
        return 0;
    }


    /**
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * 修改用户信息
     */
    public function updateUserinfo()
    {
        $data = $this->request->param();
        $update_data = array();
        if (isset($data['mobile']) && $data['mobile']) {
            $update_data['mobile'] = $data['mobile'];
        }
        if (isset($data['nickname']) && $data['nickname']) {
            $update_data['nickname'] = $data['nickname'];
        }
        if (isset($data['avatarUrl']) && $data['avatarUrl']) {
            $update_data['avatarUrl'] = $data['avatarUrl'];
        }
        $stmt = Db::name('member')
            ->where('openid', $this->openid)
            ->update($update_data);
        if ($stmt) {
            msg(0, "修改成功", []);
        } else {
            msg(-1, "修改失败", []);
        }
    }

    //获取地址列表
    public function getAddressList()
    {
        $member_id = $this->memberInfo['id'];
        $where[] = ['is_del', '=', 0];
        $where[] = ['member_id', '=', $member_id];
        $data = Db::name('member_address')
            ->where($where)
            ->order('is_default_address desc')
            ->order('create_time desc')
            ->select();
        msg(0, "查询成功", $data);
    }

    //增加收货地址
    public function addAddress()
    {
        $data = $this->request->param();
        $save_data = array(
            'member_id' => $this->memberInfo['id'],
            'realname' => $data['realname'],
            'telphone' => $data['telphone'],
            'province' => $data['province'],
            'city' => $data['city'],
            'area' => $data['area'],
            'address' => $data['address'],
            'is_default_address' => $data['is_default_address'],
            'create_time' => time()
        );
        Db::startTrans();
        try {
            if ($data['is_default_address']) {
                Db::name('member_address')
                    ->where(['member_id' => $this->memberInfo['id']])
                    ->update(['is_default_address' => 0]);
            }
            $insert_id = Db::name('member_address')->insertGetId($save_data);
            Db::commit();
            msg(0, '添加成功', $insert_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //设置默认地址
    public function setDefaultAddress()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            Db::name('member_address')
                ->where(['member_id' => $this->memberId])
                ->update(['is_default_address' => 0]);
            $num = Db::name('member_address')
                ->where(['id' => $data['id']])
                ->update([
                    'is_default_address' => 1
                ]);
            Db::commit();
            msg(0, '编辑成功', $num);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //编辑收货地址
    public function editAddress()
    {
        $data = $this->request->param();
        $save_data = array(
            'realname' => $data['realname'],
            'telphone' => $data['telphone'],
            'province' => $data['province'],
            'city' => $data['city'],
            'area' => $data['area'],
            'address' => $data['address'],
            'is_default_address' => $data['is_default_address'],
        );
        Db::startTrans();
        try {
            if ($data['is_default_address']) {
                Db::name('member_address')
                    ->where(['member_id' => $this->memberInfo['id']])
                    ->update(['is_default_address' => 0]);
            }
            $num = Db::name('member_address')
                ->where(['id' => $data['id']])
                ->update($save_data);
            Db::commit();
            msg(0, '编辑成功', $num);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    /**
     * 获取默认地址
     * @return array|\PDOStatement|string|\think\Model|void|null
     */
    public function getDefaultAddress()
    {
        $data = $this->getAddress();
        msg(0, '查询成功', $data);
    }

    public function getAddress()
    {
        $where[] = ['is_default_address', '=', 1];
        $where[] = ['is_del', '=', 0];
        $where[] = ['member_id', '=', $this->memberInfo['id']];
        $data = Db::name('member_address')->where($where)->find();
        return $data;
    }

    /**
     * 通过id获取地址
     * @return array|\PDOStatement|string|\think\Model|void|null
     */
    public function getAddress2()
    {
        $data = $this->request->param();
        $addressData = $this->getAddressById($data['id']);
        msg(0, '查询成功', $addressData);
    }

    public function getAddressById($id)
    {
        return Db::name('member_address')->find($id);
    }

    //删除地址
    public function delAddress()
    {
        $data = $this->request->param();
        $update = array(
            'id' => $data['address_id'],
            'is_del' => 1
        );
        $order_data = Db::name('member_address')->update($update);
        msg(0, "删除成功", $order_data);
    }

    /**
     * 加入购物车
     */
    public function addGoodsCar()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $where = array(
                'g.id' => $data['goods_id'],
                'g.is_del' => 0,
                'g.status' => 1,
                'gav.suk' => $data['attr_name']
            );
            $goods_info = Db::name('goods')->alias('g')
                ->join('goods_attr_value gav', 'g.id=gav.goods_id')
                ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.old_price')
                ->where($where)
                ->find();
//            $goods_info = Db::name('goods')->where(['id' => $data['goods_id']])->find();
            if (!$goods_info) {
                msg(-1, '商品不存在', '');
            }
            $is_on_car = Db::name('goods_car')->where([
                'member_id' => $this->memberId,
                'goods_id' => $data['goods_id'],
                'attr_name' => $data['attr_name']
            ])->find();
            if ($is_on_car) {
                Db::name('goods_car')->where([
                    'member_id' => $this->memberId,
                    'goods_id' => $data['goods_id'],
                    'attr_name' => $data['attr_name']
                ])->setInc('num', $data['num']);
            } else {
                $insert_data = array(
                    'goods_id' => $data['goods_id'],
                    'attr_name' => $data['attr_name'],
                    'member_id' => $this->memberId,
                    'num' => $data['num'],
                    'create_time' => time(),
                );
                Db::name('goods_car')->insertGetId($insert_data);
            }
            Db::commit();
            msg(0, '添加完成', 1);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取购物车列表
    public function getGoodsCarList()
    {
        $data_list = Db::name('goods_car')
            ->alias('gc')->join('goods g', 'gc.goods_id=g.id')
            ->field('gc.*,g.name as goods_name,g.first_img,g.desc,g.is_del as goods_is_del')
            ->where(['member_id' => $this->memberId])
            ->order('create_time desc')
            ->select();
        foreach ($data_list as $k => $v) {
            $is_buy = 1;
            $goods_attr_value = Db::name('goods_attr_value')->where([
                'goods_id' => $v['goods_id'],
                'suk' => $v['attr_name']
            ])->order('id')->find();
            if (!$goods_attr_value || $v['goods_is_del']) {
                $is_buy = 0;
            }
            $data_list[$k]['goods_attr_value'] = $goods_attr_value;
            $data_list[$k]['is_buy'] = $is_buy;
            $data_list[$k]['sumPrice'] = round($data_list[$k]['num'] * $goods_attr_value['price'], 2);
        }
        msg(0, '添加完成', $data_list);
    }

    //删除购物车商品
    public function delGoodsCarList()
    {
        $data = $this->request->param();
        Db::name('goods_car')
            ->where('id', 'in', $data['goods_car_ids'])
            ->delete();
        msg(0, '删除完成', '');
    }

    //修改购物车商品数量
    public function updateGoodsCardList()
    {
        $data = $this->request->param();
        Db::name('goods_car')
            ->where(['id' => $data['goods_car_id']])
            ->update(['num' => $data['num']]);
        msg(0, '修改完成', '');
    }

    //视频列表
    public function videoList2()
    {
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        $data_list = Db::name('video')->where($where)
            ->order('sort desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['isKan'] = $this->isKan($item['id']);
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    public function isKan($video_id)
    {
        $info = Db::name('member_video')
            ->where([
                'member_id' => $this->memberId,
                'video_id' => $video_id
            ])
            ->find();
        if ($info) {
            return 1;
        }
        return 0;
    }

    //视频详情
    public function videoDetail()
    {
        $data = $this->request->param();
        $video = Db::name('video')->find($data['id']);
        msg(0, '修改完成', $video);
    }

    //看完视频调用
    public function seeFinishVideo()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $is_kan = $this->isKan($data['id']);
            if (!$is_kan) {
                $video = Db::name('video')->find($data['id']);
                $insert_data = array(
                    'member_id' => $this->memberId,
                    'video_id' => $data['id'],
                    'points' => $video['points'],
                    'create_time' => time()
                );
                Db::name('member_video')->insertGetId($insert_data);
                addFraction($this->memberId, $video['points'], '用户看视频');
            }
//            else{
//                msg(-1, '视频已观看', '');
//            }
            Db::commit();
            msg(0, '查询成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //商城兑换
    //积分兑换 todo 测试修改
    public function fractionExchange()
    {
        $data = $this->request->param();
        $goods_info = Db::name('points_goods')->where(['id' => $data['id']])->find();
        if (!$goods_info) {
            msg(-1, '商品不存在', '');
        }
        Db::startTrans();
        try {
            if ($goods_info['points'] > $this->memberInfo['coupon1']) {
                msg(-1, '购物卷不足', '');
            }
            $insert_goods_order_data = array(
                'no' => GetOrderSN(2),
                'goods_id' => $data['id'],
                'member_id' => $this->memberId,
                'create_time' => time(),
                'points' => $goods_info['points'],
                'goods_name' => $goods_info['name'],
                'goods_img' => $goods_info['img']
            );
            $insert_goods_order_data['is_express'] = 1;
            $insert_goods_order_data['realname'] = $data['people'];
            $insert_goods_order_data['telphone'] = $data['phone'];
            $insert_goods_order_data['province'] = $data['province'];
            $insert_goods_order_data['city'] = $data['city'];
            $insert_goods_order_data['area'] = $data['area'];
            $insert_goods_order_data['address'] = $data['address'];
            $goods_order_id = Db::name('points_goods_order')->insertGetId($insert_goods_order_data);
            //兑换数量
            Db::name('points_goods')->where('id', '=', $data['id'])->setInc('sale_num');
            addGWCoupons($this->memberId, -$goods_info['points'], '', $goods_order_id, 5, '购物券兑换');
            Db::commit();
            msg(0, '兑换成功', $goods_order_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    public function fractionExchange2()
    {
        $data = $this->request->param();
        $goods_info = Db::name('goods')->find($data['goods_id']);
        if (!$goods_info) {
            msg(-1, '商品不存在', '');
        }
        if ($goods_info['goods_area'] != 5) {
            msg(-1, '非兑换区商品', '');
        }
        Db::startTrans();
        try {
            if ($goods_info['points'] > $this->memberInfo['coupon1']) {
                msg(-1, '购物卷不足', '');
            }
            //判断库存 是否可买
            $where = array(
                'g.id' => $data['goods_id'],
                'g.is_del' => 0,
                'g.status' => 1,
                'gav.suk' => $data['suk']
            );
            $goods_info = Db::name('goods')->alias('g')
                ->join('goods_attr_value gav', 'g.id=gav.goods_id')
                ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.old_price')
                ->where($where)
                ->find();
            if (!$goods_info) {
                msg(-1, '商品不存在,或下架', '');
            }
            if ($goods_info['stock'] < $data['num']) {
                msg(-1, '商品库存不足', '');
            }
            $insert_data = array(
                'order_no' => GetOrderSN(2),
                'member_id' => $this->memberId,
//                'status' => 1,//1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货 7已取消 8待取货
                'points' => $goods_info['points'],
                'pay_status' => 1,
                'create_time' => time(),
                'pay_time' => time(),
                'order_type' => $goods_info['goods_area'], //订单类型 1拼团区 2臻品区 3砍价区 4健康区
                'people' => $data['people'],
                'phone' => $data['phone'],
                'delive_type' => $data['delive_type'],
                'remark' => $data['remark']
            );
            $insert_data['origin_price'] = round($goods_info['price'] * $data['num'], 2);
            $insert_data['order_money'] = $insert_data['origin_price'];
            if ($data['delive_type'] == 1) {
                $insert_data['province'] = $data['province'];
                $insert_data['city'] = $data['city'];
                $insert_data['area'] = $data['area'];
                $insert_data['address'] = $data['address'];
                $insert_data['supply_id'] = $goods_info['supply_id'];
                $insert_data['status'] = 2;
            }
            if ($data['delive_type'] == 2) {
                $insert_data['shop_id'] = $data['shop_id'];
                $insert_data['status'] = 8;
            }
            $insert_data['shop_get_money'] = getShopMoney($insert_data);
            $order_id = Db::name('order')->insertGetId($insert_data);
            $insert_order_goods = array(
                'order_id' => $order_id,
                'goods_id' => $data['goods_id'],
                'suk' => $data['suk'],
                'num' => $data['num'],
                'price' => $goods_info['price'],
                'goods_name' => $goods_info['name'],
                'goods_img' => $goods_info['first_img'],
                'sum_money' => $data['num'] * $goods_info['price']
            );
            Db::name('order_goods')->insertGetId($insert_order_goods);
            //兑换数量
            Db::name('goods')->where('id', '=', $data['id'])->setInc('sale_num');
            addGWCoupons($this->memberId, -$goods_info['points'], '', $order_id, 5, '购物券兑换');
            Db::commit();
            msg(0, '兑换成功', $order_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }


    //兑换记录
    public function PGoodsOrderList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', 0];
        if (isset($data['status']) && $data['status']) {
            $where[] = ['status', '=', $data['status']];
        }
        $data_list = Db::name('points_goods_order')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //兑换记录最新
    public function PGoodsOrderList2()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', 0];
        $where[] = ['order_type', 'in', [5]];
        $where[] = ['member_id', '=', $this->memberId];
        if ($data['type'] == 0) {
            $where[] = ['status', 'in', [1, 2, 3, 4, 8]];
        }
        if (isset($data['type']) && $data['type']) {
            if ($data['type'] == 1) {
                $where[] = ['status', 'in', [1]];
            }
            if ($data['type'] == 2) {
                $where[] = ['status', 'in', [8]];
            }
            if ($data['type'] == 3) {
                $where[] = ['status', 'in', [2]];
            }
            if ($data['type'] == 4) {
                $where[] = ['status', 'in', [3]];
            }
            if ($data['type'] == 5) {
                $where[] = ['status', 'in', [4, 5]];
            }
        }
        $order_list = Db::name('order')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time2'] = $item['create_time'];
                $item['dai_zf_time1'] = $item['create_time'] + (60 * 15);
                $item['dai_zf_time'] = date('Y-m-d H:i:s', $item['create_time'] + (60 * 15));
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                if ($item['pay_time']) {
                    $item['pay_time'] = date('Y-m-d H:i:s', $item['pay_time']);
                }
                if ($item['tui_time']) {
                    $item['tui_time'] = date('Y-m-d H:i:s', $item['tui_time']);
                }
                $order_goods = Db::name('order_goods')
                    ->where('order_id', '=', $item['id'])
                    ->select();
                $item['order_goods'] = $order_goods;
                return $item;
            });
        msg(0, '查询成功', $order_list);
    }

    //积分明细
    public function fractionHistory()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        //cate 0收入 1支出
        $type = $data['cate'];
        $where[] = ['member_id', '=', $this->memberId];
        if ($type == 1) {
            $where[] = ['num', '>', 0];
        } elseif ($type == 2) {
            $where[] = ['num', '<', 0];
        }
        $data_list = Db::name('member_coupon1')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //购物商城顶部信息
    public function topGwCoupons()
    {
        $return['coupons'] = $this->memberInfo['coupon1'];
//        $return['coupons_msg'] = '150购物券将于06-30过期';
        $return['coupons_msg'] = '本月无过期购物卷';
        msg(0, '查询成功', $return);
    }

    /**
     * 收藏物品
     */
    public function collectGoods()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $goods_info = Db::name('goods')->where(['id' => $data['goods_id']])->find();
            if (!$goods_info) {
                msg(-1, '商品不存在', '');
            }
            $is_collect = Db::name('collect_goods')->where([
                'member_id' => $this->memberId,
                'goods_id' => $data['goods_id']
            ])->find();
            if ($is_collect) {
                msg(-2, '商品已收藏', '');
            }
            $insert_data = array(
                'create_time' => time(),
                'member_id' => $this->memberId,
                'goods_id' => $data['goods_id']
            );
            Db::name('collect_goods')->insertGetId($insert_data);
            Db::commit();
            msg(0, '添加完成', 1);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    /**
     * 取消收藏
     */
    public function cancelCollectGoods()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $goods_info = Db::name('goods')
                ->where(['id' => $data['goods_id']])
                ->find();
            if (!$goods_info) {
                msg(-1, '商品不存在', '');
            }
            $where = array(
                'member_id' => $this->memberId,
                'goods_id' => $data['goods_id']
            );
            Db::name('collect_goods')->where($where)->delete();
            Db::commit();
            msg(0, '取消收藏', 1);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }


    /**
     * 取消收藏
     */
    public function cancelCollectGoods2()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $goods_info = Db::name('goods')
                ->where('id', 'in', $data['goods_ids'])
                ->find();
//            if (!$goods_info) {
//                msg(-1, '商品不存在', '');
//            }
            $where[] = ['member_id', '=', $this->memberId];
            $where[] = ['goods_id', 'in', $data['goods_ids']];
//            $where = array(
//                'member_id' => $this->memberId,
//                'goods_id' => $data['goods_id']
//            );
            Db::name('collect_goods')->where($where)->delete();
            Db::commit();
            msg(0, '取消收藏', 1);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //判断商品是否收藏
    public function isCollect($goods_id)
    {
        $is_collect = Db::name('collect_goods')->where([
            'goods_id' => $goods_id,
            'member_id' => $this->memberId
        ])->find();
        if ($is_collect) {
            return 1;
        }
        return 0;
    }

    //收藏列表
    public function collectList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['member_id', '=', $this->memberId];
        $data_list = Db::name('collect_goods')->alias('c')
            ->join('goods g', 'c.goods_id=g.id')
            ->field('c.*,g.id as goods_id,g.name as goods_name,g.first_img,g.sale_num')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $goods_attr_value = Db::name('goods_attr_value')->where([
                    'goods_id' => $item['goods_id']
                ])->find();
                $item['goods_attr_value'] = $goods_attr_value;
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                $item['value'] = (string)$goods_attr_value['goods_id'];
                return $item;
            });
        msg(0, '查询完成', $data_list);
    }

    //获取收藏商品列表
//    public function collectList()
//    {
//        $data = $this->request->param();
//        $page = input('page/d', 1);
//        $length = input('limit/d', 100);
//        $where[] = ['c.member_id', '=', $this->memberId];
//        $where[] = ['g.status', 'in', [1, 4]];
//        $where[] = ['g.is_del', '=', 0];
//        if ($data['brand_ids']) {
//            $where[] = ['b.brand', 'in', $data['brand_ids']];
//        }
//        $goods_list = Db::name('collect_goods')
//            ->alias('c')
//            ->rightJoin('goods g', 'c.goods_id=g.id')
//            ->field('c.id as collect_id,g.*,')
//            ->where($where)
//            ->order('c.create_time desc')
//            ->paginate(
//                $length, false, [
//                    'page' => $page
//                ]
//            )->each(function ($item) use ($data) {
//                $item['value'] = (string)$item['id'];
//                $item['select'] = false;
//                return $item;
//            });
//        msg(0, '查询成功', $goods_list, $goods_list->total());
//    }

    //获取订单商品可用购物卷金额
    public function getGoodsCoupons1()
    {
        $data = $this->request->param();
        //goods_id suk num
        $coupons = 0;
        $goods_attr_data = Db::name('goods_attr_value')->where([
            'goods_id' => $data['goods_id'],
            'suk' => $data['suk'],
        ])->find();
        if ($goods_attr_data) {
            $coupons = $goods_attr_data['coupons'];
        }
        $use_coupons = $coupons * $data['num'];
        $this->memberInfo['coupon1'] >= $use_coupons ? $return_coupons = $use_coupons : $return_coupons = $this->memberInfo['coupon1'];
        $one_yuan = config('site.one_yuan_jf') ? config('site.one_yuan_jf') : 100;
        $money = round($return_coupons / $one_yuan, 2);
        $c['sum_value'] = $this->memberInfo['coupon1'];
        $c['value'] = $return_coupons;
        $c['money'] = $money;
        msg(0, '查询成功', $c);
    }

    //获取商品可用优惠卷
    public function getMemberCoupons()
    {
        $data = $this->request->param();
        $goods_attr_data = Db::name('goods_attr_value')->where([
            'goods_id' => $data['goods_id'],
            'suk' => $data['suk'],
        ])->find();
        if (!$goods_attr_data) {
            msg(-1, '商品不存在', '');
        }
        $sum_price = $goods_attr_data['price'] * $data['num'];
        $where = array(
            'member_id' => $this->memberId,
            'status' => 1,
            'is_del' => 0
        );
        $time = time();
        $where2[] = ['start_time', '<=', $time];
        $where2[] = ['end_time', '>=', $time];
        $where2[] = ['min_amount', '<=', $sum_price];
        $data_list = Db::name('member_coupons')
            ->where($where)
            ->where($where2)
            ->order('create_time desc')
            ->select();
        foreach ($data_list as $k => $v) {
            $data_list[$k]['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
            if ($v['min_amount'] <= $sum_price) {
                $data_list[$k]['is_able'] = 1;
            } else {
                $data_list[$k]['is_able'] = 0;
            }
        }
        msg(0, '查询成功', $data_list);
    }


    //判断优惠卷是否能用
    public function getMemberCouponAble()
    {
        $data = $this->request->param();
        $member_coupons_list = Db::name('member_coupons')->where([
            ['member_id', '=', $this->memberId],
            ['min_amount', '<', $data['money']],
        ])->select();
        msg(0, '创建完成', $member_coupons_list);
    }


    //订单列表
    public function orderList()
    {
        //type 0全部 1待支付 2助力中 3待发货 4待收货 5已完成
        // 0全部    1待支付  2待发货 3待收货 4已完成
        //status    1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货 7已取消 8待取货 9助力中 10砍价发起
        //order_type 1助力订单 2直接购买订单 3会员商品订单
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', 0];
        $where[] = ['order_type', 'in', [1, 2, 3, 4]];
        $where[] = ['member_id', '=', $this->memberId];
        if ($data['type'] == 0) {
            $where[] = ['status', 'in', [1, 2, 3, 4, 5]];
        }
        if (isset($data['type']) && $data['type']) {
            $where[] = ['status', 'in', $data['type']];
        }
        $order_list = Db::name('order')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time2'] = $item['create_time'];
                $item['dai_zf_time1'] = $item['create_time'] + (60 * 15);
                $item['dai_zf_time'] = date('Y-m-d H:i:s', $item['create_time'] + (60 * 15));
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                if ($item['pay_time']) {
                    $item['pay_time'] = date('Y-m-d H:i:s', $item['pay_time']);
                }
                if ($item['tui_time']) {
                    $item['tui_time'] = date('Y-m-d H:i:s', $item['tui_time']);
                }
                $order_goods = Db::name('order_goods')
                    ->where('order_id', '=', $item['id'])
                    ->find();
                $item['order_goods'] = $order_goods;
                //todo 增加助力信息
                $item['group_participants'] = Db::name('group_participants')->alias('gr')
                    ->field('gr.*,m.nickname,m.avatarUrl')
                    ->join('member m', 'm.id=gr.member_id')
                    ->order('gr.create_time')->where([
                        'gr.group_active_id' => $item['activity_id']
                    ])->select();

                return $item;
            });
        msg(0, '查询成功', $order_list);
    }

    //取消订单
    public function cancelOrder()
    {
        $data = $this->request->param();
        //修改订单状态
        //修改优惠券
        Db::startTrans();
        try {
            $order_info = Db::name('order')->where('id', '=', $data['id'])->find();
            if (!$order_info) {
                msg(-1, '订单不存在', '');
            }
            if ($order_info['status'] != 1) {
                msg(-1, '订单状态不是待支付', '');
            }
            $order_data = array(
                'id' => $data['id'],
                'status' => 7,
            );
            Db::name('order')->update($order_data);
            if ($order_info['shop_coupon'] > 0) {
                addGWCoupons2($this->memberId, $order_info['shop_coupon'], 1, $order_info['id'], 4);
            }
            Db::commit();
            msg(0, '取消成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }


    //完成收货
    public function finishOrder()
    {
        $data = $this->request->param();
        $order_info = Db::name('order')->find($data['id']);
        Db::startTrans();
        try {
            //1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
            //7已取消 8待取货 9助力中10砍价发起
            if ($order_info['status'] != 3) {
                msg(-1, '当前状态不可完成', '');
            }
            finishOrder($order_info);
            Db::commit();
            msg(0, '查询成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    //退款订单列表
    public function tuiOrderList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $type = $data['type'];
        //0全部 1处理中 2已完成
        $where[] = ['o.member_id', '=', $this->memberId];
        $where[] = ['o.status', 'in', [6]];
        if ($type == 0) {
            $where[] = ['oa.is_finish', 'in', [1, 2]];
        } else {
            $where[] = ['oa.is_finish', '=', $type];
        }
        //todo order_after 设置 最新标识
        $order_list = Db::name('order')
            ->alias('o')
            ->join('order_after oa', 'o.id=oa.order_id')
            ->field('o.*,oa.id as order_after_id, oa.create_time as oa_create_time,oa.status as oa_status,oa.is_finish')
            ->where($where)
            ->order('oa.create_time desc')->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $order_goods = Db::name('order_goods')
                    ->where('order_id', '=', $item['id'])
                    ->find();
                $item['order_goods'] = $order_goods;
                return $item;
            });
        //oa_status 2已同意 3已拒绝
        msg(0, '查询成功', $order_list);
    }

    //获取退款原因
    public function tuiReason()
    {
        $data_list = Db::name('refund_reason')
            ->where([
                'is_del' => 0,
                'status' => 1
            ])->order('sort desc')
            ->select();
        msg(0, '查询成功', $data_list);
    }


    //order-after 订单退款 status  1待同意 2已同意 3已拒绝 4已发货 5已完成
    //order-status 1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货 7已取消 8待取货 9助力中10砍价发起
    // 拒绝的恢复订单状态
    public function tuiOrder()
    {
        $data = $this->request->param();
        $order_info = Db::name('order')->find($data['id']);
        if (!$order_info) {
            msg(-1, '订单不存在', '');
        }
        //2 直接退款 3,4,5需要寄回退款 1,6无法退款 todo 上线进行关闭 助力中无法退款
        if ($order_info['status'] == 1 || $order_info['status'] == 6 || $order_info['status'] == 9) {
            msg(-1, '当前订单不可退款', '');
        }
        Db::startTrans();
        try {
            if ($order_info['status'] == 2) {
                $tui_result = tui($order_info['id']);
//                if ($tui_result['return_code'] != "FAIL") {

//                }
                if ($tui_result['result_code'] == "SUCCESS") {
                    $order_after_id = tuikuanServerOrder($order_info, $order_info['pay_money'], 0, $data['tui_reasult'], $data['imgs']);
                }
            } else {
                $order_after_id = tuikuanServerOrder2($order_info, 0, $data['tui_reasult'], $data['imgs']);
            }
            Db::commit();
            msg(0, '申请完成', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //退款详情
    public function orderTuiDetail()
    {
        $data = $this->request->param();
        $where[] = ['order_id', '=', $data['id']];
        $order_info = Db::name('order')
            ->where('id', '=', $data['id'])
            ->find();
        $order_after = Db::name('order_after')
            ->order('create_time desc')
            ->where($where)
            ->find();
        $goods_info = Db::name('order_goods')->where([
            'order_id' => $data['id']
        ])->select();
        $order_info['goods_info'] = $goods_info;
        if (!$order_after) {
            $order_info['order_after']['status'] = 0;
            msg(0, '查询完成', $order_info);
        }
        $order_after['copy_address_info'] = $order_after['people'] . $order_after['phone'] . $order_after['address'];
        $order_info['order_after'] = $order_after;

        msg(0, '查询完成', $order_info);
    }

    //退款发货
    public function tuiSendOrder()
    {
        $data = $this->request->param();
        $order_info = Db::name('order_after')
            ->where('id', '=', $data['order_after_id'])
            ->find();
        if (!$order_info) {
            msg(-2, '售后订单不存在', '');
        }
        if ($order_info['status'] != 2) {
            msg(-1, '当前售后不可退货', '');
        }
        $update = array(
            'id' => $data['order_after_id'],
            'express' => $data['express'],
            'express_no' => $data['express_no'],
            'is_send' => 1,
            'send_time' => time(),
            'status' => 4
        );
        Db::startTrans();
        try {
            Db::name('order_after')->update($update);
            Db::commit();
            msg(0, '发货完成', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //取消申请退款
    public function cancelOrderTui()
    {
        //1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
        //7已取消 8待取货 9助力中10砍价发起
        $data = $this->request->param();

        $order = Db::name('order')->find($data['id']);
        if ($order['status'] != 6) {
            msg(-1, '不可取消售后', '');
        }
        Db::name('order')->where('id', '=', $data['id'])->update([
            'status' => Db::raw('tui_before')
        ]);
        msg(0, '取消完成', '');
    }


    //判断是否新人可领取优惠券
    public function isXinPeople()
    {
        //新人优惠券 为id 1
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['coupon_id', '=', 1];
        $where[] = ['is_del', '=', 0];
        $member_coupons = Db::name('member_coupons')->where($where)->find();
        $coupon_info = Db::name('coupons')->find(1);
        if ($member_coupons) {
            msg(-1, '已领取', '');
        }
        msg(0, '查询成功', $coupon_info);
    }

    //获取新人优惠券
    public function getXinCoupons()
    {
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['coupon_id', '=', 1];
        $where[] = ['is_del', '=', 0];
        $member_coupons = Db::name('member_coupons')->where($where)->find();
        if ($member_coupons) {
            msg(-1, '已领取新人优惠券', '');
        }
        $coupon_info = Db::name('coupons')->find(1);
        if (!$coupon_info) {
            msg(-1, '新人优惠券不存在', '');
        }
        Db::startTrans();
        try {
            $result_id = getCoupons($this->memberId, $coupon_info);
            Db::commit();
            msg(0, '领取成功', $result_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //领取优惠卷
    public function getCoupons()
    {
        $data = $this->request->param();
        $coupon_info = Db::name('coupons')->where([
            'id' => $data['coupons_id'],
        ])->find();
        if (!$coupon_info) {
            msg(-1, '优惠券不存在', '');
        }
        Db::startTrans();
        try {
            //兑换优惠券
            $result_id = getCoupons($this->memberId, $coupon_info, 5);
            Db::commit();
            msg(0, '查询成功', $result_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //可领取优惠卷列表
    public function couponsList()
    {
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        $where[] = ['cate_id', '=', 2];
        $data_list = Db::name('coupons')->where($where)
            ->order('sort desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
//                $is_get = Db::name('member_coupons')->where([
//                    'member_id' => $this->memberId,
//                    'coupon_id' => $item['id'],
//                    'is_del' => 0
//                ])->find();
                if ($item['effect_type'] == 1) {
                    $item['effect_end'] = date('Y-m-d H:i:s', $item['effect_end']);
                }
                $is_get = hasReceivedCouponRecently($this->memberId, $item['id']);
                if ($is_get) {
                    $item['is_get'] = 1;
                } else {
                    $item['is_get'] = 0;
                }

                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //通过年月显示每页 签到列表
    public function signList()
    {
        $data = $this->request->param();
        //获取年 获取月
        $year = $data['year'] ? $data['year'] : date('Y', time());
        $month = $data['month'] ? $data['month'] : date('m', time());
        $fraction_num = config('site.qd_get_coupons1') ? config('site.qd_get_coupons1') : 15;
        $result = array();
        $sign_count = 0;
        $dateList = getMonthTimestamps($year, $month);
        foreach ($dateList as $k => $v) {
            $result[$k]['time'] = $v;
            $result[$k]['date'] = date('Y-m-d', $v);
            $result[$k]['date2'] = date('m.d', $v);
            $result[$k]['date3'] = date('j', $v);
            $result[$k]['weekday'] = date('w', $v);
            switch ($result[$k]['weekday']) {
                case 0:
                    $weekday_cn = "日";
                    break;
                case 1:
                    $weekday_cn = "一";
                    break;
                case 2:
                    $weekday_cn = "二";
                    break;
                case 3:
                    $weekday_cn = "三";
                    break;
                case 4:
                    $weekday_cn = "四";
                    break;
                case 5:
                    $weekday_cn = "五";
                    break;
                case 6:
                    $weekday_cn = "六";
                    break;
            }
            $result[$k]['weekday'] = $weekday_cn;
            $result[$k]['fraction_num'] = $fraction_num;
            $sign_info = Db::name('member_coupon1')->where([
                ['member_id', '=', $this->memberId],
                ['sign_time', '=', date('Y-m-d', $v)],
                ['type', '=', 1]
            ])->find();
            if ($sign_info) {
                $result[$k]['is_sign'] = 1;
                $sign_count++;
            } else {
                $now_day = date('Y-m-d', time());
                if ($now_day > $result[$k]['date']) {
                    $result[$k]['is_sign'] = -1;
                } else {
                    $result[$k]['is_sign'] = 0;
                }
            }
        }
        $return['date_list'] = $result;
        $return['sign_count'] = $sign_count;

        msg(0, '查询成功', $return);
    }

    //判断今天是否签到
    public function isSign()
    {
        $sign_info = Db::name('member_coupon1')->where([
            ['member_id', '=', $this->memberId],
            ['sign_time', '=', date('Y-m-d', time())],
            ['type', '=', 1]])->count();
        msg(0, '查询完成', $sign_info);
    }

    //会员签到
    public function sign()
    {
        //当天是否签到
        $timeRang = getTimestamp(0);
        $sign_time = date('Y-m-d', time());
        $sign_info = Db::name('member_coupon1')->where([
            ['member_id', '=', $this->memberId],
            ['sign_time', '=', $sign_time],
            ['type', '=', 1]
        ])->find();
        if ($sign_info) {
            msg(-1, '今日已签到', '');
        }
        Db::startTrans();
        try {
            $fraction_num = config('site.qd_get_coupons1') ? config('site.qd_get_coupons1') : 15;
            addGWCoupons($this->memberId, $fraction_num, '', '', 1, '签到');
            Db::commit();
            msg(0, '查询成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    // 臻品区、健康区、拼团区直接购买、砍价区直接购买
    public function createOrder()
    {
        $data = $this->request->param();
        //判断库存 是否可买
        $where = array(
            'g.id' => $data['goods_id'],
            'g.is_del' => 0,
            'g.status' => 1,
            'gav.suk' => $data['suk']
        );
        $goods_info = Db::name('goods')->alias('g')
            ->join('goods_attr_value gav', 'g.id=gav.goods_id')
            ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.old_price,gav.gong_price')
            ->where($where)
            ->find();
        if (!$goods_info) {
            msg(-1, '商品不存在,或下架', '');
        }
        if ($goods_info['stock'] < $data['num']) {
            msg(-1, '商品库存不足', '');
        }
        $data['delive_type'] = 1;
        $insert_data = array(
            'order_no' => GetOrderSN(2),
            'member_id' => $this->memberId,
            'status' => 1,//1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货 7已取消 8待取货
            'pay_status' => 0,
            'create_time' => time(),
            'order_type' => 2, //1助力订单 2直接购买订单 3会员商品订单
            'people' => $data['people'],
            'phone' => $data['phone'],
            'delive_type' => $data['delive_type'],
            'remark' => $data['remark'],
            'invite_member_id' => $this->memberInfo['invite_id']
        );
        //1拼团区 2臻品区 3砍价区 4健康区
        if ($goods_info['goods_area'] == 1) {
            $insert_data['pin_type'] = 2;
        }
        if ($goods_info['goods_area'] == 3) {
            $insert_data['can_type'] = 2;
        }
        $insert_data['province'] = $data['province'];
        $insert_data['city'] = $data['city'];
        $insert_data['area'] = $data['area'];
        $insert_data['address'] = $data['address'];
        $insert_data['supply_id'] = $goods_info['supply_id'];


        $insert_data['origin_price'] = round($goods_info['price'] * $data['num'], 2);
        $insert_data['order_money'] = $insert_data['origin_price'];
        $insert_data['pay_money'] = $insert_data['order_money'];
        //增加运费
        $insert_data['deliver_money'] = $this->getYf2($data['goods_id'], $data['suk'], $data['num'],$data['province'], $data['city'], $data['area']);
        $insert_data['pay_money'] += $insert_data['deliver_money'];

        if (isset($data['shop_coupon']) && $data['shop_coupon']) {
            $one_yuan_jf = config('site.one_yuan_jf') ? config('site.one_yuan_jf') : 100;
            $insert_data['shop_coupon'] = $data['shop_coupon'];
            $insert_data['shop_coupon_money'] = round($data['shop_coupon'] / $one_yuan_jf, 2);
            $insert_data['pay_money'] -= $insert_data['shop_coupon_money'];
        }

        $insert_data['order_money2'] = $insert_data['pay_money'];
        if (config('site.web_one_price')) {
            $insert_data['pay_money'] = 0.01;
        }
        if ($insert_data['pay_money'] <= 0) {
            msg(-1, '实际支付金额不能小于等于0', '');
        }
        Db::startTrans();
        try {
            session_start();
            $lsterRequestTime = $_SESSION[$this->memberId . 'last_time'] ?? 0;
            $currenTRequestTime = time();
            $debounce = 5;
            if ($currenTRequestTime - $lsterRequestTime < $debounce) {
                msg(-1, '下单过频繁，请稍后下单', '');
            } else {
                $_SESSION[$this->memberId . 'last_time'] = $currenTRequestTime;
            }
            $order_id = Db::name('order')->insertGetId($insert_data);
            if (isset($data['shop_coupon']) && $data['shop_coupon']) {
                addGWCoupons2($this->memberId, $data['shop_coupon'], 2, $order_id, 2);
            }
            $insert_order_goods = array(
                'order_id' => $order_id,
                'goods_id' => $data['goods_id'],
                'suk' => $data['suk'],
                'num' => $data['num'],
                'price' => $goods_info['price'],
                'goods_name' => $goods_info['name'],
                'goods_img' => $goods_info['first_img'],
                'gong_price' => $goods_info['gong_price'],
                'sum_money' => $data['num'] * $goods_info['price']
            );
            Db::name('order_goods')->insertGetId($insert_order_goods);
            Db::commit();
            msg(0, '创建完成', $insert_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //订单发起支付
    public function orderPay()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
        $userInfo = $this->memberInfo;
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $jssdk = $app->jssdk;
        $pay_money = $order_data['pay_money'] * 100;
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
        $res = $app->setSubMerchant($config['sub_mch_id'], $config['sub_appid']);
        $result = $res->order->unify([
            'body' => '商品购买',
            'out_trade_no' => $order_data['order_no'],
            'total_fee' => $pay_money,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => conf("wechat", "url") . "/orderPayNotify",
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'sub_openid' => $userInfo['openid'],
//            'openid' => $userInfo['openid'],
        ]);
        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $order_data['order_no'];
            $result['order_id'] = $order_data['id'];
            $result['type'] = 1;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }

    // 臻品区、健康区、拼团区直接购买、砍价区直接购买 订单回调
    public function orderPayBack()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            $order_no = $data['order_no'];
            $config = config('wechat.wxpay');
            $app = Factory::payment($config);
            $order_data = Db::name('order')
                ->where('order_no', '=', $order_no)
                ->find();
            //todo 支付成功测试
//            orderPaySuccess($order_data);
//            Db::commit();
//            msg(0, "支付成功！", $order_data);

            $res = $app->order->queryByOutTradeNumber($order_no);
            if ($res['trade_state'] == "SUCCESS") {
                if ($order_data['status'] == 1) {
                    orderPaySuccess($order_data);
                }
                $order_data = Db::name('order')
                    ->where('order_no', '=', $order_no)
                    ->find();
                Db::commit();
                msg(0, "支付成功！", $order_data);
            } else {
                Db::rollback();
                msg(3, $res["err_code_des"] ? $res["err_code_des"] : $res['trade_state_desc'], '');
            }
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    public function ccorderPayBack2()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            $order_no = $data['order_no'];
            $order_data = Db::name('order')
                ->where('order_no', '=', $order_no)
                ->find();
            upMemberVip2($order_data);
            Db::commit();
            msg(0, "支付成功！", $order_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }

    }

    public function orderDetail()
    {
        $data = $this->request->param();
        $return_detail = Db::name('order')->where('order_no', '=', $data['id'])->find();
        Db::startTrans();
        try {
            if (!$return_detail) {
                msg(-1, '订单不存在', '');
            }
            $return_detail['create_time'] = date('Y-m-d H:i:s', $return_detail['create_time']);
            if ($return_detail['pay_time']) {
                $return_detail['pay_time'] = date('Y-m-d H:i:s', $return_detail['pay_time']);
            }
            if ($return_detail['tui_time']) {
                $return_detail['tui_time'] = date('Y-m-d H:i:s', $return_detail['tui_time']);
            }
            if ($return_detail['send_time']) {
                $return_detail['send_time'] = date('Y-m-d H:i:s', $return_detail['send_time']);
            }
            $order_goods = Db::name('order_goods')
                ->where('order_id', '=', $return_detail['id'])
                ->select();
            $return_detail['order_goods'] = $order_goods;
            $group_participants = Db::name('group_participants')->alias('gr')
                ->field('gr.*,m.nickname,m.avatarUrl')
                ->join('member m', 'm.id=gr.member_id')
                ->order('gr.create_time')->where([
                    'gr.group_active_id' => $return_detail['activity_id']
                ])->select();
            if ($return_detail['order_type'] == 1) {
                $group_activities = Db::name('group_activities')->where('id', '=', $return_detail['activity_id'])->find();
                $group_activities['now_member_id'] = $this->memberId;
                $return_detail['group_activities'] = $group_activities;

                $return_detail['need_num'] = $group_activities['group_num'] - $group_activities['now_num'];
            }

            $return_detail['group_participants'] = $group_participants;
            Db::commit();
            msg(0, '查询成功', $return_detail);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //判断是否可以发起助力
    public function isCanPinCreate()
    {
        msg(0, '可以发起', 1);
//        $can_zli = $this->isCanPinCreate2();
//        if ($can_zli == 1) {
//            msg(0, '可以发起', 1);
//        }
//        msg(-1, '请购买“助力商品”后获取发起助力资格。', 0);
    }

    public function isCanPinCreate2()
    {
        return $this->memberInfo['is_create_zl'];
    }

    //发起助力订单
    public function creatPTOrder()
    {
        $data = $this->request->param();
//        if ($this->memberInfo['is_create_zl'] == 0) {
//            msg(-2, '当前不能发起助力', '');
//        }
        if ($this->memberInfo['coupon1'] < $data['shop_coupon']) {
            msg(-3, '积分不足', '');
        }
        $where = array(
            'g.id' => $data['goods_id'],
            'g.is_del' => 0,
            'g.status' => 1,
            'gav.suk' => $data['suk']
        );
        $goods_info = Db::name('goods')->alias('g')
            ->join('goods_attr_value gav', 'g.id=gav.goods_id')
            ->field('g.*,gav.suk,gav.stock,gav.sale_num,
            gav.price,
            gav.old_price,
            gav.pin_price')
            ->where($where)
            ->find();
        if ($goods_info['is_can_zl'] != 1) {
            msg(-1, '商品不可助力', '');
        }
        if (!$goods_info) {
            msg(-1, '商品不存在,或下架', '');
        }
        if ($goods_info['stock'] < $data['num']) {
            msg(-1, '商品库存不足', '');
        }
        //order_type 订单类型 1拼团区 2臻品区 3砍价区 4健康区
        $data['delive_type'] = 1;
        $insert_data = array(
            'order_no' => GetOrderSN(2),
            'member_id' => $this->memberId,
            'status' => 1,//1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货 7已取消 8待取货 9助力中10砍价发起
            'pay_status' => 0,
            'create_time' => time(),
            'order_type' => 1,
            'people' => $data['people'],
            'phone' => $data['phone'],
            'pin_sort' => 1,
            'delive_type' => $data['delive_type'],
            'remark' => $data['remark'],
            'invite_member_id' => $this->memberInfo['invite_id']
        );
        $insert_data['province'] = $data['province'];
        $insert_data['city'] = $data['city'];
        $insert_data['area'] = $data['area'];
        $insert_data['address'] = $data['address'];
        $insert_data['supply_id'] = $goods_info['supply_id'];

        $insert_data['origin_price'] = round($goods_info['price'] * $data['num'], 2);
        $insert_data['order_money'] = $insert_data['origin_price'];
        $insert_data['pay_money'] = $insert_data['order_money'];

        //增加运费
        $insert_data['deliver_money'] = $this->getYf2($data['goods_id'], $data['suk'], $data['num'],$data['province'], $data['city'], $data['area']);
        $insert_data['pay_money'] += $insert_data['deliver_money'];

        if (isset($data['shop_coupon']) && $data['shop_coupon']) {
            $one_yuan_jf = config('site.one_yuan_jf') ? config('site.one_yuan_jf') : 100;
            $insert_data['shop_coupon'] = $data['shop_coupon'];
            $insert_data['shop_coupon_money'] = round($data['shop_coupon'] / $one_yuan_jf, 2);
            $insert_data['pay_money'] -= $insert_data['shop_coupon_money'];
        }

        $insert_data['order_money2'] = $insert_data['pay_money'];
        if (config('site.web_one_price')) {
            $insert_data['pay_money'] = 0.01;
        }
        if ($insert_data['pay_money'] <= 0) {
            msg(-1, '实际支付金额不能小于等于0', '');
        }

        Db::startTrans();
        try {
            session_start();
            $lsterRequestTime = $_SESSION[$this->memberId . 'last_time'] ?? 0;
            $currenTRequestTime = time();
            $debounce = 5;
            if ($currenTRequestTime - $lsterRequestTime < $debounce) {
                msg(-1, '下单过频繁，请稍后下单', '');
            } else {
                $_SESSION[$this->memberId . 'last_time'] = $currenTRequestTime;
            }
            $order_id = Db::name('order')->insertGetId($insert_data);
            if (isset($data['shop_coupon']) && $data['shop_coupon']) {
                addGWCoupons2($this->memberId, $data['shop_coupon'], 2, $order_id, 2);
            }
            $insert_order_goods = array(
                'order_id' => $order_id,
                'goods_id' => $data['goods_id'],
                'suk' => $data['suk'],
                'num' => $data['num'],
                'price' => $goods_info['pin_price'],
                'goods_name' => $goods_info['name'],
                'goods_img' => $goods_info['first_img'],
                'sum_money' => $data['num'] * $goods_info['pin_price']
            );
            Db::name('order_goods')->insertGetId($insert_order_goods);
            Db::commit();
            msg(0, '创建完成', $insert_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //拼团发起支付
    public function PtOrderPay()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
        $userInfo = $this->memberInfo;
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $jssdk = $app->jssdk;
        $pay_money = $order_data['pay_money'] * 100;
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
        $result = $app->order->unify([
            'body' => '商品购买',
            'out_trade_no' => $order_data['order_no'],
            'total_fee' => $pay_money,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => conf("wechat", "url") . "/ptNotify", // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $userInfo['openid'],
        ]);
        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $order_data['order_no'];
            $result['order_id'] = $order_data['id'];
            $result['type'] = 1;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }


    //获取拼团卷数量
    public function getPtCoupons()
    {
        msg(0, '查询成功', $this->memberInfo['coupon2']);
    }

    //拼团卷支付
    public function PtCouponsPay()
    {
        $data = $this->request->param();
        $order_info = Db::name('order')
            ->where('order_no', '=', $data['order_no'])
            ->find();
        if (!$order_info) {
            msg(-1, '订单不存在', '');
        }
        if ($order_info['order_money'] > $this->memberInfo['coupon2']) {
            msg(-2, '拼团卷不足', '');
        }
        if ($order_info['status'] != 1) {
            msg(-3, '订单状态错误', '');
        }
        PtOrderPaySuccess($order_info, 2);
        addPTCoupons($order_info['member_id'], -$order_info['order_money'], $order_info['id'], 2, '拼团使用');
        $return_order = Db::name('order')->find($order_info['id']);
        msg(0, '支付完成', $return_order);
    }


    //获取发起拼团订单详情
    public function getPtOrderDetail()
    {
        $data = $this->request->param();
//        $group_activities_id = $data['group_activities_id'];
        $order_info = Db::name('order')->where([
            'order_no' => $data['order_no']
//            'activity_id' => $group_activities_id,
//            'member_id' => $this->memberId
        ])->find();
        $order_goods = Db::name('order_goods')->where([
            'order_id' => $order_info['id']
        ])->find();
        $where = array(
            'g.id' => $order_goods['goods_id'],
//            'g.is_del' => 0,
//            'g.status' => 1,
            'gav.suk' => $order_goods['suk']
        );
        $goods_info = Db::name('goods')->alias('g')
            ->join('goods_attr_value gav', 'g.id=gav.goods_id')
            ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.pin_price')
            ->where($where)
            ->find();
        $goods_info['num'] = $order_goods['num'];
        $group_activities = Db::name('group_activities')->find($order_info['activity_id']);
        $group_participants = Db::name('group_participants')->alias('gr')
            ->field('gr.*,m.nickname,m.avatarUrl')
            ->join('member m', 'm.id=gr.member_id')
            ->order('gr.create_time')->where([
                'gr.group_active_id' => $order_info['activity_id']
            ])->select();
        $c_num = $group_activities['group_num'] - count($group_participants);
        for ($i = $c_num; $i > 0; $i--) {
            $group_participants[] = [];
        }
        $return_data['order_info'] = $order_info;
        $return_data['goods_info'] = $goods_info;
        $group_activities['now_member_id'] = $this->memberId;
        $return_data['group_activities'] = $group_activities;
        $return_data['group_participants'] = $group_participants;
        msg(0, '查询完成', $return_data);
    }

    //获取分享拼团详情
    public function getPtOrderDetail2()
    {
        $data = $this->request->param();
        $group_activities_id = $data['group_activities_id'];
        $group_activities = Db::name('group_activities')->find($group_activities_id);

        $order_info = Db::name('order')->where([
            'activity_id' => $group_activities_id,
            'member_id' => $group_activities['member_id']
        ])->find();
        $order_goods = Db::name('order_goods')->where([
            'order_id' => $order_info['id']
        ])->find();
        $where = array(
            'g.id' => $order_goods['goods_id'],
            'gav.suk' => $order_goods['suk']
        );
        $goods_info = Db::name('goods')->alias('g')
            ->join('goods_attr_value gav', 'g.id=gav.goods_id')
            ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.pin_price')
            ->where($where)
            ->find();

        $group_participants = Db::name('group_participants')->alias('gr')
            ->field('gr.*,m.nickname,m.avatarUrl')
            ->join('member m', 'm.id=gr.member_id')
            ->order('gr.create_time')->where([
                'gr.group_active_id' => $group_activities_id
            ])->select();
        $c_num = $group_activities['group_num'] - count($group_participants);
        for ($i = $c_num; $i > 0; $i--) {
            $group_participants[] = [];
        }
        $return_data['order_info'] = $order_info;
        $return_data['goods_info'] = $goods_info;
        $return_data['group_activities'] = $group_activities;
        $return_data['group_participants'] = $group_participants;
        msg(0, '查询完成', $return_data);
    }


    //判断是否可以参加拼团
    public function isCanPin()
    {
        $data = $this->request->param();
        isCanPin($data['group_activities_id'], $this->memberId);
        msg(0, '查询成功', '');
    }

    //创建参加拼团订单
    public function addPt()
    {
        $data = $this->request->param();
        //是否可参与助力
        isCanPin($data['group_activities_id'], $this->memberId);
        //获取活动
        $pin_order = Db::name('order')->where([
            'activity_id' => $data['group_activities_id'],
            'pin_sort' => 1,
            'order_type' => 1
        ])->find();
        //获取拼团的商品
        $pin_order_goods = Db::name('order_goods')->where(['order_id' => $pin_order['id']])->find();
        $where = array(
            'g.id' => $pin_order_goods['goods_id'],
            'g.is_del' => 0,
            'g.status' => 1,
            'gav.suk' => $data['suk']
        );
        $goods_info = Db::name('goods')->alias('g')
            ->join('goods_attr_value gav', 'g.id=gav.goods_id')
            ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.old_price,gav.pin_price')
            ->where($where)
            ->find();
        if (!$goods_info) {
            msg(-1, '商品不存在,或下架', '');
        }
        if ($goods_info['stock'] < $data['num']) {
            msg(-1, '商品库存不足', '');
        }
        $data['delive_type'] = 1;
        $insert_data = array(
            'order_no' => GetOrderSN(2),
            'member_id' => $this->memberId,
            'status' => 1,//1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货 7已取消 8待取货 9助力中10砍价发起
            'pay_status' => 0,
            'create_time' => time(),
            'order_type' => 1,
            'people' => $data['people'],
            'phone' => $data['phone'],
            'delive_type' => $data['delive_type'],
            'activity_id' => $data['group_activities_id'],
            'remark' => $data['remark'],
            'invite_member_id' => $this->memberInfo['invite_id']
        );
        $insert_data['province'] = $data['province'];
        $insert_data['city'] = $data['city'];
        $insert_data['area'] = $data['area'];
        $insert_data['address'] = $data['address'];
        $insert_data['supply_id'] = $goods_info['supply_id'];

        $insert_data['origin_price'] = round($goods_info['price'] * $data['num'], 2);
        $insert_data['order_money'] = $insert_data['origin_price'];
        $insert_data['pay_money'] = $insert_data['order_money'];

        //增加运费
        $insert_data['deliver_money'] = $this->getYf2($pin_order_goods['goods_id'], $data['suk'], $data['num'],$data['province'], $data['city'], $data['area']);
        $insert_data['pay_money'] += $insert_data['deliver_money'];


        if (isset($data['shop_coupon']) && $data['shop_coupon']) {
            $one_yuan_jf = config('site.one_yuan_jf') ? config('site.one_yuan_jf') : 100;
            $insert_data['shop_coupon'] = $data['shop_coupon'];
            $insert_data['shop_coupon_money'] = round($data['shop_coupon'] / $one_yuan_jf, 2);
            $insert_data['pay_money'] -= $insert_data['shop_coupon_money'];
        }

        $insert_data['order_money2'] = $insert_data['pay_money'];
        if (config('site.web_one_price')) {
            $insert_data['pay_money'] = 0.01;
        }
        if ($insert_data['pay_money'] <= 0) {
            msg(-1, '实际支付金额不能小于等于0', '');
        }
        Db::startTrans();
        try {
            session_start();
            $lsterRequestTime = $_SESSION[$this->memberId . 'last_time'] ?? 0;
            $currenTRequestTime = time();
            $debounce = 5;
            if ($currenTRequestTime - $lsterRequestTime < $debounce) {
                msg(-1, '下单过频繁，请稍后下单', '');
            } else {
                $_SESSION[$this->memberId . 'last_time'] = $currenTRequestTime;
            }
            $order_id = Db::name('order')->insertGetId($insert_data);
            if (isset($data['shop_coupon']) && $data['shop_coupon']) {
                addGWCoupons2($this->memberId, $data['shop_coupon'], 2, $order_id, 2);
            }
            $insert_order_goods = array(
                'order_id' => $order_id,
                'goods_id' => $pin_order_goods['goods_id'],
                'suk' => $data['suk'],
                'num' => $data['num'],
                'price' => $goods_info['pin_price'],
                'goods_name' => $goods_info['name'],
                'goods_img' => $goods_info['first_img'],
                'sum_money' => $data['num'] * $goods_info['pin_price']
            );
            Db::name('order_goods')->insertGetId($insert_order_goods);
            Db::commit();
            msg(0, '创建完成', $insert_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //参加拼团发起支付
    public function PtOrderPay2()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
//        isCanPin($order_data['activity_id'], $this->memberId);
        $userInfo = $this->memberInfo;
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $jssdk = $app->jssdk;
        $pay_money = $order_data['pay_money'] * 100;
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
        $result = $app->order->unify([
            'body' => '助力购买',
            'out_trade_no' => $order_data['order_no'],
            'total_fee' => $pay_money,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => conf("wechat", "url") . "/ptNotify2",
//            'notify_url' => conf("wechat", "url") . '/pdOrderNotify', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $userInfo['openid'],
        ]);

        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $order_data['order_no'];
            $result['order_id'] = $order_data['id'];
            $result['type'] = 1;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }

    //创建参加拼团订单 支付回调
    public function PtOrderPayBack2()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            $order_no = $data['order_no'];
            $config = config('wechat.wxpay');
            $app = Factory::payment($config);
            $order_data = Db::name('order')
                ->where('order_no', '=', $order_no)
                ->find();
            //todo 测试
//            PtOrderPaySuccess2($order_data);
//            die();
//            Db::commit();
//            msg(0, "支付成功！", $order_data);

            $res = $app->order->queryByOutTradeNumber($order_no);
            if ($res['trade_state'] == "SUCCESS") {
                if ($order_data['status'] == 1) {
                    PtOrderPaySuccess2($order_data);
                }
                $order_data = Db::name('order')
                    ->where('order_no', '=', $order_no)
                    ->find();
                Db::commit();
                msg(0, "支付成功！", $order_data);
            } else {
                Db::rollback();
                msg(3, $res["err_code_des"] ? $res["err_code_des"] : $res['trade_state_desc'], '');
            }
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //我的拼团
    public function myPtList()
    {
        //1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
        //7已取消 8待取货 9助力中10砍价发起
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $type = $data['type']; //0全部 1进行中 2已完成
//        $where[] = ['o.pin_type', '=', 1];
        $where[] = ['o.order_type', '=', 1];
        $where[] = ['o.status', 'in', [2, 3, 4, 8, 9]];
        $where[] = ['o.member_id', '=', $this->memberId];
        if ($type == 0) {
            $where[] = ['ga.status', 'in', [1, 2]];
        }
        if ($type == 1) {
            $where[] = ['ga.status', '=', 1];
        }
        if ($type == 2) {
            $where[] = ['ga.status', '=', 2];
        }
        $order_list = Db::name('order')->alias('o')
            ->join('group_activities ga', 'o.activity_id=ga.id')
            ->field('o.*,ga.group_num,ga.now_num,ga.status as ga_status')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $order_goods = Db::name('order_goods')->where([
                    'order_id' => $item['id']
                ])->find();
//                $item['order_goods']=$order_goods;
                $goods_info_where = array(
                    'g.id' => $order_goods['goods_id'],
//            'g.is_del' => 0,
//            'g.status' => 1,
                    'gav.suk' => $order_goods['suk']
                );
                $goods_info = Db::name('goods')->alias('g')
                    ->join('goods_attr_value gav', 'g.id=gav.goods_id')
                    ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.pin_price')
                    ->where($goods_info_where)
                    ->find();
                $goods_info['num'] = $order_goods['num'];
                $item['goods_info'] = $goods_info;
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);

                $item['group_participants'] = Db::name('group_participants')->alias('gr')
                    ->field('gr.*,m.nickname,m.avatarUrl')
                    ->join('member m', 'm.id=gr.member_id')
                    ->order('gr.create_time')->where([
                        'gr.group_active_id' => $item['activity_id']
                    ])->select();
                $group_activities = Db::name('group_activities')->find($item['activity_id']);
                if ($group_activities['member_id'] == $this->memberId) {
                    $item['is_gan'] = 1;
                } else {
                    $item['is_gan'] = 0;
                }

                return $item;
            });
        msg(0, '查询完成', $order_list);
    }


    //获取用户信息顶部卷
    public function myTopCoupons()
    {
        //coupons
        $where = array(
            'member_id' => $this->memberId,
            'status' => 1,
            'is_del' => 0
        );
        $time = time();
        $where2[] = ['start_time', '<=', $time];
        $where2[] = ['end_time', '>=', $time];
        $coupons_count = Db::name('member_coupons')
            ->where($where)
            ->where($where2)
            ->order('create_time desc')
            ->count();
        $return_data['a'] = $this->memberInfo['coupon1'];
        $return_data['b'] = $this->memberInfo['coupon2'];
        $return_data['c'] = $coupons_count;
        msg(0, '查询成功', $return_data);
    }

    //我的优惠卷列表
    public function getMemberCouponsList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $data_list = Db::name('member_coupons')->where([
            'status' => 1,
            'member_id' => $this->memberId,
            'is_del' => 0
        ])->order('create_time desc')
            ->paginate($length, false, ['page' => $page])->each(function ($item) {
                //start_time    end_time
                $item['start_time'] = date('Y-m-d H:i:s', $item['start_time']);
                $item['end_time'] = date('Y-m-d H:i:s', $item['end_time']);
                $item['back_img_url'] = config('site.coupons_bg');
                $item['open'] = 0;
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //判断用户是否可发起砍价
    public function isCreateBargain()
    {
        //判断是否新人 老人才能砍价
        //一个品只能发起一次砍价(成功、进行中) todo
        $data = $this->request->param();
        $goods = $data['goods_id'];
        if ($this->memberInfo['level_id'] < 2) {
            msg(-1, "当前等级不能砍价", 1);
        }
        msg(0, "查询成功", 1);
    }

    //发起砍价
    public function createBargain()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            //suk goods_id
            $where = array(
                'g.id' => $data['goods_id'],
                'g.is_del' => 0,
                'g.status' => 1,
                'gav.suk' => $data['suk']
            );
            $goods_info = Db::name('goods')->alias('g')
                ->join('goods_attr_value gav', 'g.id=gav.goods_id')
                ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.min_price')
                ->where($where)
                ->find();
            if (!$goods_info) {
                msg(-1, '商品不存在,或下架', '');
            }
            $insert_data = array(
                'goods_id' => $data['goods_id'],
                'suk' => $data['suk'],
                'member_id' => $this->memberId,
                'price' => $goods_info['price'],
                'current_price' => $goods_info['price'],
                'target_price' => $goods_info['min_price'],
                'bargain_times' => 0,
                'max_bargain_times' => $goods_info['bargain_count'],
                'create_time' => time(),
                'end_time' => time() + ($goods_info['bargain_time'] * 60),
            );
            $bargain_activity_id = Db::name('bargain_activity')->insertGetId($insert_data);
            $insert_data['id'] = $bargain_activity_id;
            //1随机金额2固定金额
            if ($goods_info['sj_kan'] == 1) {
                $bargain_money_list = bargain($goods_info['price'], $goods_info['min_price'], $goods_info['bargain_count']);
            } else {
                $bargain_money_list = averageBargain($goods_info['price'], $goods_info['min_price'], $goods_info['bargain_count']);
            }
            foreach ($bargain_money_list as $k => $v) {
                $bargain_money_insert = array(
                    'cut_amount' => $v['cut_amount'],
                    'current_price' => $v['current_price'],
                    'ba_id' => $bargain_activity_id,
                    'sort' => $k + 1
                );
                Db::name('bargain_money')->insertGetId($bargain_money_insert);
            }
            Db::commit();
            msg(0, "创建成功", $insert_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //是否可砍价
    public function isCanBargain()
    {
        $data = $this->request->param();
        isCanBargain($data['bargain_activity_id'], $this->memberId);
        msg(0, "查询成功", 1);
    }

    //参与砍价
    public function joinBargain()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            isCanBargain($data['bargain_activity_id'], $this->memberId);
            $bargain_record_data = bargainJoin($data['bargain_activity_id'], $this->memberId);
            bargainFinish($data['bargain_activity_id']);
            Db::commit();
            msg(0, "助力成功", $bargain_record_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }


    //砍价记录
    public function getBargainRecord()
    {
        $data = $this->request->param();
        $group_participants = Db::name('bargain_record')->alias('br')
            ->field('br.*,m.nickname,m.avatarUrl')
            ->join('member m', 'm.id=br.member_id')
            ->order('br.create_time')->where([
                'br.activity_id' => $data['bargain_activity_id']
            ])->select();
        foreach ($group_participants as $k => $v) {
            $group_participants[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
        }
        $bargain_activity = Db::name('bargain_activity')->find($data['bargain_activity_id']);
        $c_num = $bargain_activity['max_bargain_times'] - count($group_participants);
        for ($i = $c_num; $i > 0; $i--) {
            $group_participants[] = [];
        }
        msg(0, '查询完成', $group_participants, count($group_participants));
    }

    //我的砍价列表
    public function myBargainList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $type = $data['type']; //0全部 1进行中 2已完成
        $where[] = ['ba.member_id', '=', $this->memberId];
        $where[] = ['ba.is_c', '=', 1];
        if ($type == 0) {
            $where[] = ['ba.bargain_status', 'in', [1, 2, 3]];
        }
        if ($type == 1) {
            $where[] = ['ba.bargain_status', 'in', [1]];
        }
        if ($type == 2) {
            $where[] = ['ba.bargain_status', 'in', [2, 3]];
        }
        $bargain_list = Db::name('bargain_activity')->alias('ba')
            ->join('goods g', 'g.id=ba.goods_id')
            ->field('ba.*,g.name as goods_name,g.first_img')
            ->order('ba.create_time desc')
            ->where($where)
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $bargain_record = Db::name('bargain_record')->alias('br')
                    ->field('br.*,m.nickname,m.avatarUrl')
                    ->join('member m', 'm.id=br.member_id')
                    ->order('br.create_time')->where([
                        'br.activity_id' => $item['id']
                    ])->select();
                $item['count_num'] = count($bargain_record);
                $item['bargain_record'] = $bargain_record;
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        msg(0, '查询完成', $bargain_list);
    }


    //砍价发起支付
    public function bargainOrderPay()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
        $userInfo = $this->memberInfo;
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $jssdk = $app->jssdk;

        $pay_money = $order_data['pay_money'] * 100;
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
        $res = $app->setSubMerchant($config['sub_mch_id'], $config['sub_appid']);
        $result = $res->order->unify([
            'body' => '商品购买',
            'out_trade_no' => $order_data['order_no'],
            'total_fee' => $pay_money,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => conf("wechat", "url") . "/bargainOrderPayNotify",
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'sub_openid' => $userInfo['openid'],
//            'openid' => $userInfo['openid'],
        ]);
        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $order_data['order_no'];
            $result['order_id'] = $order_data['id'];
            $result['type'] = 1;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }

    //砍价支付回调
    public function bargainOrderPayBack()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            $order_no = $data['order_no'];
            $config = config('wechat.wxpay');
            $app = Factory::payment($config);
            $order_data = Db::name('order')
                ->where('order_no', '=', $order_no)
                ->find();
            $res = $app->order->queryByOutTradeNumber($order_no);
            if ($res['trade_state'] == "SUCCESS") {
                if ($order_data['status'] == 10) {
                    bargainOrderSuccess2($order_data);
                }
                $order_data = Db::name('order')
                    ->where('order_no', '=', $order_no)
                    ->find();
                Db::commit();
                msg(0, "支付成功！", $order_data);
            } else {
                Db::rollback();
                msg(3, $res["err_code_des"] ? $res["err_code_des"] : $res['trade_state_desc'], '');
            }
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //判断是否可以申请小店
    public function isCanApplyShop()
    {

        // -1 为不能申请
        $shop_info = Db::name('shop')->where([
            'member_id' => $this->memberId,
            'is_del' => 0
        ])->find();
        if ($shop_info && $shop_info['status'] == 0) {
            msg(1, "审核中", '');
        }
        if ($shop_info && $shop_info['status'] == 3) {
            msg(0, "可申请", '');
        }
        if ($this->memberInfo['level_id'] >= 3) {
            msg(0, "可申请", '');
        }
        $result = isShop($this->memberId);
        if ($result == -1) {
            msg(-1, "不可以申请", '');
        } else {
            msg(0, "可申请", '');
        }
    }

    //申请小店
    public function applyShop()
    {
        $data = $this->request->param();
        $business_data = Db::name('shop')
            ->where('is_del', 0)
            ->where(['member_id' => $this->memberId])
            ->find();
        if ($business_data && $business_data['status'] != 3) {    //存在且不是审核失败
            msg(-1, '您已申请,请勿重复提交', '');
        }
        $create_time = time();
        $insert_data = array(
            'member_id' => $this->memberId,
//            'province' => $data['province'],
//            'city' => $data['city'],
//            'area' => $data['area'],
            'address' => $data['address'],
            'shop_name' => $data['shop_name'],
            'people' => $data['people'],
            'phone' => $data['phone'],
            'create_time' => $create_time,
            'latitude' => $data['latitude'],
            'longitude' => $data['longitude'],
        );
        $time = explode('-', $data['operate_time']);
        $insert_data['start_time'] = $time[0];
        $insert_data['end_time'] = $time[1];
        if ($data['remark']) {
            $insert_data['remark'] = $data['remark'];
        }
        $data_list = getAddressByLocation2($data['latitude'], $data['longitude']);
        $data_list = json_decode($data_list, true);
        if ($data_list['code'] == 0) {
            $address_info = $data_list['data']['address_component'];
            $insert_data['province'] = $address_info['province'];
            $insert_data['city'] = $address_info['city'];
            $insert_data['area'] = $address_info['district'];
        }
        Db::startTrans();
        try {
            //重新提交
            if ($business_data && $business_data['status'] == 3) {
                unset($insert_data['member_id']);
                $insert_data['status'] = 0;
                $business2_id = Db::name('shop')
                    ->where([
                        'is_del' => 0,
                        'member_id' => $this->memberId
                    ])->update($insert_data);
                Db::name('shop_img')->where('shop_id', $business_data['id'])->delete();
                $business_id = $business_data['id'];
            } else {
                $business_id = Db::name('shop')->insertGetId($insert_data);
            }
            foreach ($data['operate_img'] as $k => $v) {
                $insert_img_data = array(
                    'shop_id' => $business_id,
                    'sort' => $k + 1,
                    'img' => $v
                );
                Db::name('shop_img')->insertGetId($insert_img_data);
            }
            Db::commit();
            msg(0, '查询成功', $business_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }

    }

    /**
     * 获取成为商家审核状态
     */
    public function getShopStatus()
    {
        $data = Db::name('shop')->where(['member_id' => $this->memberId, 'is_del' => 0])->find();
        if ($data) {
            if ($data['status'] == 1) {
                //返回数据
                msg(0, '申请已通过', $data);
            }
            if ($data['status'] == 3) {
                //返回数据
                msg(-3, '审核不通过', $data);
            }
            if ($data['status'] == 2) {
                //返回数据
                msg(-2, '账户冻结,请联系管理员', $data);
            }
            msg(1, '你已申请，等待审核', '');
        }
        msg(-1, '未申请', '');
    }


    public function getShopList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];
        $city = $data['city'];
//        $range = input('range/d', 50000);
        $where[] = ['province|city', '=', $city];
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];

//        $latRange = $range / 111320;
//        $lngRange = $range / (111320 * cos(deg2rad($latitude)));
//        $minLat = $latitude - $latRange;
//        $maxLat = $latitude + $latRange;
//        $minLng = $longitude - $lngRange;
//        $maxLng = $longitude + $lngRange;
//        $where[] = ['latitude', 'between', [$minLat, $maxLat]];
//        $where[] = ['longitude', 'between', [$minLng, $maxLng]];

        $result = [];
        $data_list = Db::name('shop')
            ->where($where)
            ->page($page, $length)
            ->select();
        if (count($data_list) == 0) {
            msg(0, '查询成功', '');
        }
        if (!$latitude || !$longitude) {
            msg(0, '查询成功', '');
        }
        foreach ($data_list as $k => $v) {
            $distance = distanceHaversine($latitude, $longitude, $v['latitude'], $v['longitude']) * 1000;
//            if ($distance <= $range) {
            $v['distance'] = round($distance);
            $result[] = $v;
//            }
        }
        usort($result, function ($a, $b) {
            return $a['distance'] - $b['distance'];
        });
        foreach ($result as $k => $v) {
            if ($k == 0) {
                $result[$k]['is_select'] = 2;
                $result[$k]['is_distance'] = 1;
            } else {
                $result[$k]['is_select'] = 1;
                $result[$k]['is_distance'] = 2;
            }
        }
        //todo 测试经纬度距离是否正确
        msg(0, '查询成功', $result, count($result));
    }

    //获取最近商店
    public function getShopDistance()
    {
        $data = $this->request->param();
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];
        $city = $data['city'];
        $where[] = ['province|city', '=', $city];
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        $data_list = Db::name('shop')
            ->where($where)
            ->select();
        if (count($data_list) == 0) {
            msg(0, '查询成功', '');
        }
        if (!$latitude || !$longitude) {
            msg(0, '查询成功', '');
        }
        foreach ($data_list as $k => $v) {
            $distance = distanceHaversine($latitude, $longitude, $v['latitude'], $v['longitude']) * 1000;
            $v['distance'] = round($distance);
            $result[] = $v;
        }
        usort($result, function ($a, $b) {
            return $a['distance'] - $b['distance'];
        });
        msg(0, '查询成功', $result[0]);
    }

    //账户中心四个
    public function accountCenter()
    {
        //可提现
        $a = $this->memberInfo['money'];
        $b = Db::name('reward')->where([
            'member_id' => $this->memberId,
            'status' => 0
        ])->sum('money');
        $c = Db::name('member_finance')->where([
            ['member_id', '=', $this->memberId],
            ['type', '=', 6],
            ['is_kuan', '=', 0],
        ])->sum('money');
        $d = Db::name('member_finance')->where([
            ['member_id', '=', $this->memberId],
            ['type', '=', 6],
            ['is_kuan', '=', 1],
        ])->sum('money');
        $return['a'] = $a;
        $return['b'] = $b;
        $return['c'] = $c;
        $return['d'] = $d;
        msg(0, '查询成功', $return);
    }

    //提现
    public function tixian()
    {
        $data = $this->request->param();
        if ($data['money'] <= 0) {
            msg(-1, '输入正确值', '');
        }
        if ($data['money'] > $this->memberInfo['money']) {
            msg(-1, '提现金额不能大于余额', '');
        }
//        if ($data['money'] < $this->memberInfo['min_tx']) {
//            msg(-2, '最低提现金额' . $this->memberInfo['min_tx'], '');
//        }
        Db::startTrans();
        try {
            $insert_data = array(
                'member_id' => $this->memberId,
                'money' => $data['money'],
                'type' => 6,
                'tixian_type' => $data['tixian_type'], //1银行 2支付宝 3微信
                'tixian_account' => $data['tixian_account'], //提现账号
                'tixian_name' => $data['tixian_name'],//提现人姓名
                'tixian_bank' => $data['tixian_bank'],//提现银行名（银行提现使用）
                'desc' => '余额提现',
                'status' => 0,//'0未完成 待审核 1已完成 审核完成 提现使用',
                'create_time' => time(),
                'is_count' => 2
            );
            $insert_data['shou_money'] = round($data['money'] * (0.07), 2);
            $insert_data['shou_money'] = 0;
            $insert_data['true_money'] = $data['money'] - $insert_data['shou_money'];
            $insert_id = Db::name('member_finance')->insertGetId($insert_data);
            Db::name('member')
                ->where('id', '=', $this->memberId)
                ->setDec('money', $data['money']);
            Db::commit();
            msg(0, '申请成功', $insert_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //提现记录
    public function tixianList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['type', '=', 6];
        $data_list = Db::name('member_finance')
            ->where($where)
            ->order('create_time desc')
            ->page($page, $length)
            ->select();
        foreach ($data_list as $k => $v) {
            $data_list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            $data_list[$k]['status_time'] = date('Y-m-d H:i:s', $v['status_time']);
            $data_list[$k]['kuan_time'] = date('Y-m-d H:i:s', $v['kuan_time']);
        }
        msg(0, '查询成功', $data_list);
    }
    //分销订单列表
    //我的下线
    //我的团队
    public function myTeam()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $cort_type = $data['cort_type'];
        if ($cort_type == 1) {
            $sort = 'create_time desc';
        } else {
            $sort = 'create_time';
        }
        $where[] = ['invite_id', '=', $this->memberId];
        $data_list = Db::name('member')->where($where)
            ->order($sort)
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                $item['money'] = Db::name('reward')->where([
                    ['junior_member_id', '=', $item['id']],
                    ['member_id', '=', $this->memberId],
                    ['status', '=', 1],
                ])->sum('money');
                $item['order_num'] = Db::name('reward')->where([
                    ['junior_member_id', '=', $item['id']],
                    ['member_id', '=', $this->memberId],
                    ['status', '=', 1],
                ])->count();
                $team_num = Db::name('member')->where('invite_id', '=', $item['id'])->count();
                $item['team_num'] = $team_num;
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    public function PtCGw()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            if ($data['coupon2'] <= 0) {
                msg(-1, '请输入正确数量', '');
            }
            if ($data['coupon2'] > $this->memberInfo['coupon2']) {
                msg(-2, '请输入正确数量', '');
            }
            addPTCoupons($this->memberId, -$data['coupon2'], '', 3, '转换购物卷');
            addGWCoupons($this->memberId, $data['coupon2'], '', '', 4, '拼团卷兑换');
            Db::commit();
            msg(0, '兑换成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //拼团卷明细
    public function PTCouponsHistory()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        //cate 0收入 1支出
        $type = $data['cate'];
        $where[] = ['member_id', '=', $this->memberId];
        if ($type == 1) {
            $where[] = ['num', '>', 0];
        } elseif ($type == 2) {
            $where[] = ['num', '<', 0];
        }
        $data_list = Db::name('member_coupon2')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //分销订单
    public function shouDetailList()
    {
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['member_id', '=', $this->memberId];
        $order_list = Db::name('reward')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                $item['member_info'] = Db::name('member')->field('nickname,avatarUrl')->find($item['junior_member_id']);
                $item['goods_info'] = Db::name('goods')->field('name,first_img')->find($item['goods_id']);
                $price = Db::name('goods_attr_value')->where([
                    'goods_id' => $item['goods_id']
                ])->find();
                $item['goods_info']['price'] = $price['price'];
                return $item;
            });
        msg(0, '查询成功', $order_list);
    }


    /**
     * Desc 创建订单
     * Create on 2024/10/22 9:50
     * Create by wangyafang
     */
    public function create()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $param = $this->request->post();

        $param['wechat_id'] = User::getWechatId($this->auth->id);

        $create_data = array(
            'wechat_id' => $param['wechat_id'],
            'order_no' => wddj_create_order(),
            'price' => $param['price'],
            'order_id' => $param['order_id'],
        );
        $this->model->allowField(true)->save($create_data);

        try {
            $openid = wddj_get_openid($param['wechat_id']);
            $conf = Wxapp::unify('追加费用', $create_data['order_no'], $create_data['price'], $openid, request()->domain() . '/api/wddj/user/order_additional_price_log/order_additional_notify');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('微信预支付调用成功', array(
            'id' => $this->model->id,
            'conf' => $conf,
        ));
    }

    //获取订单商品可用购物卷金额
    public function getYf()
    {
        $data = $this->request->param();
        $yf = $this->getYf2($data['goods_id'], $data['suk'], $data['num'], $data['province'], $data['city'], $data['area']);
        msg(0, '查询完成', $yf);
    }

    //获取
    public function getYf2($goods_id, $suk, $num, $province, $city, $area)
    {
        //获取商品属性
        $goods_attr_data = Db::name('goods_attr_value')->where([
            'goods_id' => $goods_id,
            'suk' => $suk,
        ])->find();
        $goods_money = $goods_attr_data['price'] * $num;
        //商品信息
        $goods_info=Db::name('goods')->find($goods_id);
        //获取商品品牌
        $goods_brand=Db::name('brand')->find($goods_info['brand_id']);
        //获取运费模板
        $yfcm=Db::name('yfcm')->where('id','=',$goods_brand['yfcm_id'])->find();
        if ($yfcm){

            //获取分类邮费
            $yfc_where[] = ['city', '=', $city];
            $yfc_where[] = ['province', '=', $province];
            $yfc_where[] = ['ycm_id', '=', $yfcm['id']];

            $city_yfc = Db::name('yfc')->where([
                ['ycm_id', '=', $yfcm['id']],
                ['city', '=', $city],
            ])->find();
            //存在二级地区
            if ($city_yfc){
                if ($goods_money >= $city_yfc['mj']) {
                    return 0;
                } else {
                    return $city_yfc['fee'];
                }
            }
            //一级区域
            $province_yfc = Db::name('yfc')->where([
                ['ycm_id', '=', $yfcm['id']],
                ['province', '=', $province],
                ['city', '=', null],
            ])->find();
            if ($province_yfc){
                if ($goods_money >= $province_yfc['mj']) {
                    return 0;
                } else {
                    return $province_yfc['fee'];
                }
            }
            if ($goods_money >= $yfcm['mj']) {
                return 0;
            } else {
                return $yfcm['fee'];
            }


        }else{
            $y_fee = config('site.y_fee') ? config('site.y_fee') : 6;
            $by_money = config('site.mj_by') ? config('site.mj_by') : 50;
            if ($goods_money >= $by_money) {
                return 0;
            } else {
                return $y_fee;
            }
        }
    }

    //积分
    public function jfAccountCenter()
    {
        $a = $this->memberInfo['coupon1'];
        $b = Db::name('order')->where([
            ['member_id', '=', $this->memberId],
            ['order_type', 'in', [1]],
            ['zl_status', 'in', [1]],
        ])->sum('get_jf');
        $c = Db::name('member_coupon1')->where([
            ['member_id', '=', $this->memberId],
            ['type', '=', 3],
            ['is_kuan', '=', 0],
        ])->sum('num');
        $d = Db::name('member_coupon1')->where([
            ['member_id', '=', $this->memberId],
            ['type', '=', 3],
            ['is_kuan', '=', 1],
        ])->sum('num');
        $return['a'] = $a;
        $return['b'] = $b;
        $return['c'] = $c;
        $return['d'] = $d;
        msg(0, '查询成功', $return);
    }

    //积分列表
    public function jfList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['member_id', '=', $this->memberId];
        //type 0全部 1收入 2支出
        if (isset($data['type']) && $data['type']) {
            $where[] = ['is_count', '=', $data['type']];
        }
        $data_list = Db::name('member_coupon1')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        msg(0, '查询完成', $data_list);
    }

    //积分提现
    public function jfTx()
    {
        $data = $this->request->param();
        if ($data['num'] <= 0) {
            msg(-1, '输入正确值', '');
        }
        if ($data['num'] > $this->memberInfo['coupon1']) {
            msg(-2, '提现金额不能大于余额', '');
        }
        Db::startTrans();
        try {
            $one_yuan_jf = config('site.one_yuan_jf') ? config('site.one_yuan_jf') : 100;
            $moeny = round($data['num'] / $one_yuan_jf, 2);
            $insert_data = array(
                'member_id' => $this->memberId,
                'num' => $data['num'],
                'moeny' => $moeny,
                'type' => 3,
                'tixian_type' => $data['tixian_type'], //1银行 2支付宝 3微信
                'tixian_account' => $data['tixian_account'], //提现账号
                'tixian_name' => $data['tixian_name'],//提现人姓名
                'tixian_bank' => $data['tixian_bank'],//提现银行名（银行提现使用）
                'desc' => '提现',
                'create_time' => time(),
                'is_count' => 2
            );
            $insert_id = Db::name('member_coupon1')->insertGetId($insert_data);
            Db::name('member')->where(['id' => $this->memberId])->setDec('coupon1', $data['num']);
            Db::commit();
            msg(0, '申请成功', $insert_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //取消助力订单
    public function cancelZl()
    {
        //助力状态 1助力中 2已完成 3放弃助力
        //zl_status
        $data = $this->request->param();
        Db::startTrans();
        try {
            $order_info = Db::name('order')->find($data['order_id']);
            if ($order_info['status'] != 9) {
                msg(-1, '当前状态不是助力中', '');
            }
            Db::name('order')->update([
                'id' => $data['order_id'],
                'zl_status' => 3,
                'status' => 2
            ]);
            Db::commit();
            msg(0, '取消完成', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //会员订单购买
    public function createOrder2()
    {
        $data = $this->request->param();
        //判断库存 是否可买
        $where = array(
            'g.id' => $data['goods_id'],
            'g.is_del' => 0,
            'g.status' => 1,
            'gav.suk' => $data['suk'],
            'goods_area' => 2
        );
        $goods_info = Db::name('goods')->alias('g')
            ->join('goods_attr_value gav', 'g.id=gav.goods_id')
            ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.old_price,gav.gong_price')
            ->where($where)
            ->find();
        if (!$goods_info) {
            msg(-1, '商品不存在,或下架', '');
        }
        if ($goods_info['stock'] < $data['num']) {
            msg(-1, '商品库存不足', '');
        }
        $data['delive_type'] = 1;
        $insert_data = array(
            'order_no' => GetOrderSN(2),
            'member_id' => $this->memberId,
            'status' => 1,//1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货 7已取消 8待取货
            'pay_status' => 0,
            'create_time' => time(),
            'order_type' => 3, //1助力订单 2直接购买订单 3会员商品订单
            'people' => $data['people'],
            'phone' => $data['phone'],
            'delive_type' => $data['delive_type'],
            'remark' => $data['remark'],
            'invite_member_id' => $this->memberInfo['invite_id'],
//            'fx_member_id' => $data['member_id']
        );
        if (is_numeric($data['member_id'])) {
            $insert_data['fx_member_id'] = $data['member_id'];
        }
        $insert_data['province'] = $data['province'];
        $insert_data['city'] = $data['city'];
        $insert_data['area'] = $data['area'];
        $insert_data['address'] = $data['address'];
        $insert_data['supply_id'] = $goods_info['supply_id'];


        $insert_data['origin_price'] = round($goods_info['price'] * $data['num'], 2);
        $insert_data['order_money'] = $insert_data['origin_price'];
        $insert_data['pay_money'] = $insert_data['order_money'];
        //增加运费
        $insert_data['deliver_money'] = $this->getYf2($data['goods_id'], $data['suk'], $data['num'],$data['province'], $data['city'], $data['area']);
        $insert_data['pay_money'] += $insert_data['deliver_money'];

        if (isset($data['shop_coupon']) && $data['shop_coupon']) {
            $one_yuan_jf = config('site.one_yuan_jf') ? config('site.one_yuan_jf') : 100;
            $insert_data['shop_coupon'] = $data['shop_coupon'];
            $insert_data['shop_coupon_money'] = round($data['shop_coupon'] / $one_yuan_jf, 2);
            $insert_data['pay_money'] -= $insert_data['shop_coupon_money'];
        }

        $insert_data['order_money2'] = $insert_data['pay_money'];
        if (config('site.web_one_price')) {
            $insert_data['pay_money'] = 0.01;
        }
        if ($insert_data['pay_money'] <= 0) {
            msg(-1, '实际支付金额不能小于等于0', '');
        }
        Db::startTrans();
        try {
            session_start();
            $lsterRequestTime = $_SESSION[$this->memberId . 'last_time'] ?? 0;
            $currenTRequestTime = time();
            $debounce = 5;
            if ($currenTRequestTime - $lsterRequestTime < $debounce) {
                msg(-1, '下单过频繁，请稍后下单', '');
            } else {
                $_SESSION[$this->memberId . 'last_time'] = $currenTRequestTime;
            }
            $order_id = Db::name('order')->insertGetId($insert_data);
            if (isset($data['shop_coupon']) && $data['shop_coupon']) {
                addGWCoupons2($this->memberId, $data['shop_coupon'], 2, $order_id, 2);
            }
            $insert_order_goods = array(
                'order_id' => $order_id,
                'goods_id' => $data['goods_id'],
                'suk' => $data['suk'],
                'num' => $data['num'],
                'price' => $goods_info['price'],
                'goods_name' => $goods_info['name'],
                'goods_img' => $goods_info['first_img'],
                'gong_price' => $goods_info['gong_price'],
                'sum_money' => $data['num'] * $goods_info['price']
            );
            Db::name('order_goods')->insertGetId($insert_order_goods);
            Db::commit();
            msg(0, '创建完成', $insert_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //会员订单发起支付
    public function orderPay2()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
        $userInfo = $this->memberInfo;
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $jssdk = $app->jssdk;
        $pay_money = $order_data['pay_money'] * 100;
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
        $res = $app->setSubMerchant($config['sub_mch_id'], $config['sub_appid']);
        $result = $res->order->unify([
            'body' => '商品购买',
            'out_trade_no' => $order_data['order_no'],
            'total_fee' => $pay_money,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => conf("wechat", "url") . "/orderPayNotify2",
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'sub_openid' => $userInfo['openid'],
        ]);
        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $order_data['order_no'];
            $result['order_id'] = $order_data['id'];
            $result['type'] = 1;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }

    //订单奖励列表
    public function getOrderJfList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['o.member_id', '=', $this->memberId];
        //1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货
        //7已取消 8待取货 9助力中10砍价发起
        $where[] = ['o.status', 'in', [4, 5]];
        $where[] = ['o.order_type', 'in', [3]];
        //0全部 1领取中 2领取完成
        //0未完成 1已完成
        if (isset($data['type']) && $data['type']) {
            if ($data['type'] == 1) {
                $where[] = ['ojr.status', 'in', [0]];
            }
            if ($data['type'] == 2) {
                $where[] = ['ojr.status', 'in', [1]];
            }
        }
        $order_list = Db::name('order')
            ->alias('o')
            ->join('order_jf_return ojr', 'o.id=ojr.order_id')
            ->where($where)
            ->field('o.*,ojr.id as ojr_id,ojr.status as ojr_status,ojr.day_num,ojr.sum_jf,ojr.create_time as ojr_create_time,ojr.now_day,ojr.now_jf')
            ->order('o.finish_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                setGetJf($item['id']);
                $item['ojr_create_time'] = date('Y-m-d H:i:s', $item['ojr_create_time']);
                $order_goods = Db::name('order_goods')
                    ->where('order_id', '=', $item['id'])
                    ->find();
                $item['order_goods'] = $order_goods;
                //未领失效天数
                $item['no_day_num'] = Db::name('order_jf_return_detail')->where([
                    ['end_timestamp', '<', time()],
                    ['order_id', '=', $item['id']],
                    ['is_get', 'in', [0, 2]]
                ])->count();
                //待领天数
                $item['dai_day_num'] = Db::name('order_jf_return_detail')->where([
                    ['start_timestamp', '>', time()],
                    ['order_id', '=', $item['id']],
                ])->count();
                return $item;
            });
        msg(0, '查询成功', $order_list);
    }



    //会员商品列表
    //创建会员订单
    //会员订单发起支付
    //会员支付回调
    //会员订单完成逻辑
    //奖励列表
    //领取详情
    public function getJfOrderDetail()
    {
        $data = $this->request->param();
        $return_detail = Db::name('order')
            ->where('id', '=', $data['order_id'])
            ->find();
        Db::startTrans();
        try {
            if (!$return_detail) {
                msg(-1, '订单不存在', '');
            }
            $return_detail['create_time'] = date('Y-m-d H:i:s', $return_detail['create_time']);
            if ($return_detail['pay_time']) {
                $return_detail['pay_time'] = date('Y-m-d H:i:s', $return_detail['pay_time']);
            }
            if ($return_detail['tui_time']) {
                $return_detail['tui_time'] = date('Y-m-d H:i:s', $return_detail['tui_time']);
            }
            if ($return_detail['send_time']) {
                $return_detail['send_time'] = date('Y-m-d H:i:s', $return_detail['send_time']);
            }
            $order_goods = Db::name('order_goods')
                ->where('order_id', '=', $return_detail['id'])
                ->find();
            $return_detail['order_goods'] = $order_goods;
            //领取信息
            $order_jf_return = Db::name('order_jf_return')
                ->where('order_id', '=', $return_detail['id'])
                ->find();
            $return_detail['order_jf_return'] = $order_jf_return;
//            $order_jf_return_detail=Db::name('order_jf_return_detail')->where([
//                ['order_id','=',$return_detail['id']]
//            ])->order('day')->select();
//            $return_detail['order_jf_return_detail'] = $order_jf_return_detail;
//
//            setGetJf($return_detail['id']);
            Db::commit();
            msg(0, '查询成功', $return_detail);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //领取详情列表
    public function detailDay()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 30);
        //设置签到过期
//        setGetJf($data['order_id']);
        $order_jf_return_detail = Db::name('order_jf_return_detail')->where([
            ['order_id', '=', $data['order_id']]
        ])->order('day')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                return $item;
            });
        msg(0, '查询成功', $order_jf_return_detail);
    }

    public function isGetByOrder()
    {
        $data = $this->request->param();

        $order_jf_return = Db::name('order_jf_return')->where([
            ['order_id', '=', $data['order_id']],
        ])->find();
        if ($order_jf_return['status'] == 1) {
            msg(0, '查询成功', 1);
        }
        $day = date('Y-m-d');
        $order_jf_return_detail = Db::name('order_jf_return_detail')->where([
            ['order_id', '=', $data['order_id']],
            ['date', '=', $day],
        ])->find();

        if ($order_jf_return_detail['is_get'] == 1) {
            $data = 1;
        } else {
            $data = 0;
        }
        msg(0, '查询成功', $data);
    }

    //领取详情列表
    public function detailDay2()
    {
        $data = $this->request->param();
        $order_id = $data['order_id'];
        $order_jf_return = Db::name('order_jf_return')
            ->where('order_id', '=', $order_id)
            ->find();
        // $days=$order_jf_return['create_time']->diff(time());
        $secondsDiff = abs(time() - $order_jf_return['create_time']) / (60 * 60 * 24);
        $daysDiff = floor($secondsDiff / (60 * 60 * 24)) + 1;
        $day = mapNumberToRange($daysDiff);
        //todo
        msg(0, '查询成功', $day);
    }

    //签到当前应该第几页
    public function detailDay3()
    {
        $data = $this->request->param();
        $order_id = $data['order_id'];
        $order_jf_return = Db::name('order_jf_return')
            ->where('order_id', '=', $order_id)
            ->find();

        $secondsDiff = abs(time() - $order_jf_return['create_time']) / (60 * 60 * 24);
        $daysDiff = floor($secondsDiff / (60 * 60 * 24)) + 1;
        $day = mapNumberToRange($daysDiff);
        msg(0, '查询成功', $day);
    }

    //积分订单领取
    public function getOrderJf()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            //设置签到过期
//            setGetJf($data['order_id']);
            $now_day = date('Y-m-d');
            $where[] = ['order_id', '=', $data['order_id']];
            $where[] = ['date', '=', $now_day];
            $where[] = ['is_get', '=', 0];
            $order_jf_return = Db::name('order_jf_return')
                ->where('order_id', '=', $data['order_id'])
                ->find();
            $order_jf_return_detail = Db::name('order_jf_return_detail')
                ->where($where)
                ->find();
            if (!$order_jf_return_detail) {
                msg(-1, '今日已领取', '');
            }
            Db::name('order_jf_return_detail')->where($where)->update([
                'is_get' => 1,
                'get_time' => time()
            ]);
            Db::name('order_jf_return')
                ->where('order_id', '=', $data['order_id'])->update([
                    'now_jf' => Db::raw('now_jf+' . $order_jf_return_detail['points']),
                    'now_day' => Db::raw('now_day+' . 1)
                ]);
            if ($order_jf_return['day_num'] == $order_jf_return_detail['day']) {
                Db::name('order_jf_return')
                    ->where('order_id', '=', $data['order_id'])->update([
                        'status' => 1,
                    ]);
            }
            addGWCoupons2($this->memberId, $order_jf_return_detail['points'], 1, $data['order_id'], 5);
            Db::commit();
            msg(0, '领取完成', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //发起助力
    public function createZl()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            //suk goods_id
            $where = array(
                'g.id' => $data['goods_id'],
                'g.is_del' => 0,
                'g.status' => 1,
                'gav.suk' => $data['suk']
            );
            $goods_info = Db::name('goods')->alias('g')
                ->join('goods_attr_value gav', 'g.id=gav.goods_id')
                ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.min_price')
                ->where($where)
                ->find();
            if ($goods_info['is_can_zl'] != 1) {
                msg(-1, '商品不可助力', '');
            }
            if (!$goods_info) {
                msg(-1, '商品不存在,或下架', '');
            }
            $one_yuan_jf = config('site.one_yuan_jf') ? config('site.one_yuan_jf') : 100;
            $sum_jf = $goods_info['price'] * $data['num'] * $one_yuan_jf * ($goods_info['rate'] / 100);
            $insert_data = array(
                'goods_id' => $data['goods_id'],
                'suk' => $data['suk'],
                'member_id' => $this->memberId,
                'price' => $goods_info['price'],
                'current_price' => $goods_info['price'],
                'target_price' => $goods_info['price'],
                'bargain_times' => 0,
                'max_bargain_times' => $goods_info['pin_num'],
                'goods_num' => $data['num'],
                'create_time' => time(),
                'end_time' => time() + ($goods_info['bargain_time'] * 60),
                'sum_jf' => $sum_jf
            );
            $bargain_activity_id = Db::name('bargain_activity')->insertGetId($insert_data);
            $insert_data['id'] = $bargain_activity_id;
            //1随机金额2固定金额
//            if ($goods_info['sj_kan'] == 1) {
//                $bargain_money_list = bargain($goods_info['price'], $goods_info['min_price'], $goods_info['bargain_count']);
//            } else {
//                $bargain_money_list = averageBargain($goods_info['price'], $goods_info['min_price'], $goods_info['bargain_count']);
//            }
//            foreach ($bargain_money_list as $k => $v) {
//                $bargain_money_insert = array(
//                    'cut_amount' => $v['cut_amount'],
//                    'current_price' => $v['current_price'],
//                    'ba_id' => $bargain_activity_id,
//                    'sort' => $k + 1
//                );
//                Db::name('bargain_money')->insertGetId($bargain_money_insert);
//            }
            Db::commit();
            msg(0, "创建成功", $insert_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //助力邀请
    public function zlyq()
    {
        Db::startTrans();
        try {
            $data = $this->request->param();
            Db::name('bargain_activity')->update([
                'id' => $data['bargain_activity_id'],
                'is_c' => 1
            ]);
//bargain_activity
            Db::commit();
            msg(0, "邀请完成", '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //创建助力订单
    public function createBargainOrder()
    {
        $data = $this->request->param();

        $bargain_activity = Db::name('bargain_activity')->find($data['bargain_activity_id']);
        $data['num'] = $bargain_activity['goods_num'];
        //todo 上线放开
        if (!$bargain_activity || $bargain_activity['status'] != 1) {
            msg(-1, '助力未完成', '');
        }
        if ($this->memberInfo['coupon1'] < $data['shop_coupon']) {
            msg(-3, '积分不足', '');
        }
        //创建砍价订单
        $where = array(
            'g.id' => $bargain_activity['goods_id'],
            'g.is_del' => 0,
            'g.status' => 1,
            'gav.suk' => $bargain_activity['suk']
        );
        $goods_info = Db::name('goods')->alias('g')
            ->join('goods_attr_value gav', 'g.id=gav.goods_id')
            ->field('g.*,gav.suk,gav.stock,gav.sale_num,gav.price,gav.old_price,gav.gong_price')
            ->where($where)
            ->find();
        if (!$goods_info) {
            msg(-1, '商品不存在,或下架', '');
        }
        if ($goods_info['stock'] < $data['num']) {
            msg(-1, '商品库存不足', '');
        }
        $data['delive_type'] = 1;
        $insert_data = array(
            'order_no' => GetOrderSN(2),
            'member_id' => $this->memberId,
            'status' => 10,//1待支付 2待发货 3待收货 4已完成 5已评价 6售后退货 7已取消 8待取货  9拼团中 10助力发起
            'pay_status' => 0,
            'create_time' => time(),
            'order_type' => 1, //订单类型 1拼团区 2臻品区 3砍价区 4健康区
//            'order_type' => $goods_info['goods_area'], //订单类型 1拼团区 2臻品区 3砍价区 4健康区
            'people' => $data['people'],
            'phone' => $data['phone'],
            'delive_type' => $data['delive_type'],
            'remark' => $data['remark'],
//            'can_type' => 1,
            'bargain_activity_id' => $bargain_activity['id'],
            'sum_jf' => $bargain_activity['sum_jf'],
//            'cut_money' => $bargain_activity['price'] - $bargain_activity['current_price']
        );
        $insert_data['province'] = $data['province'];
        $insert_data['city'] = $data['city'];
        $insert_data['area'] = $data['area'];
        $insert_data['address'] = $data['address'];
        $insert_data['supply_id'] = $goods_info['supply_id'];

        $insert_data['origin_price'] = round($goods_info['price'] * $data['num'], 2);
        $insert_data['order_money'] = $insert_data['origin_price'];
        $insert_data['pay_money'] = $insert_data['order_money'];

        //增加运费 修改运费是0
        $insert_data['deliver_money'] = $this->getYf2($bargain_activity['goods_id'], $bargain_activity['suk'], 1,$data['province'], $data['city'], $data['area']);
        $insert_data['pay_money'] += $insert_data['deliver_money'];

        if (isset($data['shop_coupon']) && $data['shop_coupon']) {
            $one_yuan_jf = config('site.one_yuan_jf') ? config('site.one_yuan_jf') : 100;
            $insert_data['shop_coupon'] = $data['shop_coupon'];
            $insert_data['shop_coupon_money'] = round($data['shop_coupon'] / $one_yuan_jf, 2);
            $insert_data['pay_money'] -= $insert_data['shop_coupon_money'];
        }
        $insert_data['order_money2'] = $insert_data['pay_money'];

        if (config('site.web_one_price')) {
            $insert_data['pay_money'] = 0.01;
        }
        if ($insert_data['pay_money'] <= 0) {
            msg(-1, '实际支付金额不能小于等于0', '');
        }
        Db::startTrans();
        try {
            $order_id = Db::name('order')->insertGetId($insert_data);
            if (isset($data['shop_coupon']) && $data['shop_coupon']) {
                addGWCoupons2($this->memberId, $data['shop_coupon'], 2, $order_id, 2);
            }
            $insert_order_goods = array(
                'order_id' => $order_id,
                'goods_id' => $bargain_activity['goods_id'],
                'suk' => $bargain_activity['suk'],
                'num' => $data['num'],
                'price' => $goods_info['price'],
                'goods_name' => $goods_info['name'],
                'goods_img' => $goods_info['first_img'],
                'gong_price' => $goods_info['gong_price'],
                'sum_money' => $data['num'] * $goods_info['price']
            );
            Db::name('order_goods')->insertGetId($insert_order_goods);
            Db::commit();
            msg(0, '创建完成', $insert_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //助力订单是否需要邮费
    public function zlisyf()
    {
        msg(0, '需要', 1);
    }

    //参与助力记录
    public function joinZlList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['br.member_id', '=', $this->memberId];
        $type = $data['type']; //0未发放 1已发放
        if ($type == 0) {
            $where[] = ['ba.is_f', 'in', [0]];
        }
        if ($type == 1) {
            $where[] = ['ba.is_f', 'in', [1]];
        }
        $bargain_record_list = Db::name('bargain_record')
            ->alias('br')
            ->join('bargain_activity ba', 'ba.id=br.activity_id')
            ->field('br.*,ba.goods_id,ba.suk,ba.sum_jf,ba.order_no,ba.bargain_times,ba.current_price,ba.max_bargain_times')
            ->order('br.create_time desc')
            ->where($where)->paginate($length, false,
                ['page' => $page])
            ->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                $goods_info = Db::name('goods')->find($item['goods_id']);
                $item['goods_info'] = $goods_info;
                $per_jf = $item['sum_jf'] / ($item['max_bargain_times'] + 1);
                $item['per_jf'] = round($per_jf);
                return $item;
            });
        msg(0, '查询完成', $bargain_record_list);
    }

    //助理订单 助力活动关联时间
    public function setData1()
    {
        Db::name('bargain_activity')
            ->where('id', '<>', 0)
            ->update([
                'is_f' => 0,
            ]);
        $zl_order = Db::name('order')->where([
            ['order_type', '=', 1],
            ['status', 'in', [4, 5]]
        ])->select();
        foreach ($zl_order as $k => $v) {
            Db::name('bargain_activity')
                ->where('order_no', '=', $v['order_no'])
                ->update([
                    'is_f' => 1,
                    'f_time' => $v['finish_time']
                ]);
        }
    }
    // 台湾省 香港特别行政区 澳门特别行政区

    //邀请助力
    //用户助力
    //创建助力订单
    //助理订单支付
    //订单完成返回积分
    //设置商品比例
    //设置代理商品比例返现
    //修改订单列表
    //修改返现逻辑
    //修改后台


    //todo 增加积分锁定 取消订单积分恢复 addGWCoupons2 创建订单加入 1
    // 下订单测试 退款相关接口测试 调整退款逻辑，退回积分，后台退款，退款管理，配置小程序支付，证书申请，订单管理修改，用户积分提现管理，配合前端修改接口
    // 所有订单运费、取消助力 不会返回积分 1
    // 退款设置详细 未发货可直接退款 已发货进入后台审核 1
    // 商品购买后 可以进行发起助力 1
    // 三级关联设置代理 助力订单返现 完成订单返现 1
    // 取消助力 申请退款 1
    // 退款详情 1
    // 助力订单 支付完成后 生成返回积分 1
    // invite_member_id 创建订单时增加 1
    // 收货地址是区域代理的进行返现 订单完成加入 1
    // 运费 助力订单暂时不加 代码加上运费 注释掉 1
    // 拼团详细测试 退款测试 走通 1
    // 提现管理 订单管理 代理提现管理 1
    // 助力管理 1
    // 设置上级时查看是否做限制 1
    // 订单完成再返积分 1
    // 首页数据 1
    // 自动取消，自动收货 1
    // 用户协议 1
    // 附件管理 1
    // 检查参与拼团
    // 下订单测试 退款相关接口测试 调整退款逻辑，退回积分，后台退款，退款管理，配置小程序支付，证书申请，订单管理修改，用户积分提现管理，配合前端修改接口
    //  助力订单完成返回积分 修改逻辑，送货商订单发货后台，后台助力管理 助力详情、记录，附件管理修改，代理提现管理，配合前端修改接口 上传数据；运费逻辑修改
    //  购买配置oss banner上传 商品图上传 ，拼团逻辑修改，配送商后台售后订单管理  自动取消，自动收货 首页数据 配合前端修改接口 修改后台退款逻辑，青岛汽配微信支付修改配置，
    // 后台各项搜索
    // 青岛汽配支付设置 1
    // 配置oss 1
    // 订单完成进行分积分修改 1
    // 代理奖励分好 助力订单 1
    // 取消代理返现比例 1
    // 订单列表修改
    // 订单修改助力商品逻辑 购买完 1
    // 对接 子商户微信支付记录 虚拟发货 1
    // 银河商城后台会员商品增加分享返现比例；接口增加会员分享返现积分，下单测试；助力商品修改，订单退款；北京陪诊客户沟通
    // 单独的退款接口 注册快递100账号
    // 增加助力记录接口
    // 对接微信接口的确认收货  供货商价格 供货商后台管理修改  供货商价格统计 增肌比例百分比
    // 助力订单确认收货后增加 bargain_activity is_f 积分是否发放 0未发放 1已发放
    // 汽配项目配合前端修改接口 增加数据，首页秒杀接口；银河商城 客户会议；客户沟通 服务器购买；修改助力接口 增加助力发起，参与助力记录 测试，后台修改；
    // 供应商价格1
    // 下单增加供应商价格1
    // 后台供应商管理 供应商订单金额统计 确认收货
    // 新项目沟通 银河商城服务器宝塔环境搭建 迁移项目 修改测试 后台商品编辑添加供货价
    // 再次发起支付修改
    // 卖卡项目逻辑梳理；银河商城 后台供应商订单统计 商品供货价；分权设置 创建订单增加供货价 测试

}
